SQLALChemy.query:类';Car';的未解析属性引用';查询';
问题描述
我有一个这里已经提到的问题 https://youtrack.jetbrains.com/issue/PY-44557但是我还找不到解决方案。我正在结合使用Python Flask和SQLAlChemy来创建API服务。
以下是我的导入内容:
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float
import os
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'dealers.db')
db = SQLAlchemy(app)
ma = Marshmallow(app)
以下是我的数据模型:
class Car(db.Model):
__tablename__ = 'cars'
car_id = Column(Integer, primary_key=True)
car_name = Column(String)
car_type = Column(String)
class CarSchema(ma.Schema):
class Meta:
fields = ('car_id', 'car_name', 'car_type')
car_schema = CarSchema()
cars_schema = CarSchema(many=True)
当我使用.query
时,我的UDF出现问题/警告def cars():
car_list = Car.query.all() # *Unresolved attribute reference 'query' for class 'Car'
result = cars_schema.dump(car_list)
return jsonify(result)
解决方案
我已经了解了如何使用type-hinting stubs为此问题提供详细的部分解决方案。
在单独的文件和同名的存根文件中创建派生自db.Model
的抽象Python类
示例:
abstract.py:
class AbstractBaseModel(db.Model):
__abstract__ = True
abstract.pyi:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import orm
from sqlalchemy.ext.declarative import DeclarativeMeta
db: SQLAlchemy = SQLAlchemy()
class _FBase(db.Model):
query: orm.Query
class AbstractBaseModel(_FBase, DeclarativeMeta):
...
然后创建从抽象派生的模型。AbstractBaseModel而不是db.Model
例如:
from abstract import AbstractBaseModel
class Car(AbstractBaseModel):
__tablename__ = 'cars'
car_id = Column(Integer, primary_key=True)
car_name = Column(String)
car_type = Column(String)
我还创建了用于测试此解决方法的sample project
相关文章