属性错误:类型对象'Product'没有属性'all'烧瓶?



这是我的Flask应用程序的完整代码:

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/test'
# Order matters: Initialize SQLAlchemy before Marshmallow
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
price = db.Column(db.Float)

class ProductSchema(ma.ModelSchema):
class Meta:
model = Product
@app.route('/')
def hello_world():
products = Product.all()
products_schema = ProductSchema(many=true)
output = products_schema.dump(products).data
return jsonify(output)

如您所见,我尝试从Product模型中提取数据:

products = Product.all()

我收到此错误:

request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:ProjectsDistbackendindex.py", line 27, in hello_world
products = Product.all()
AttributeError: type object 'Product' has no attribute 'all'

您忘记使用.query属性访问查询对象;.all()是该对象上的方法:

products = Product.query.all()

从 Flask-SQLAchemy 文档的查询协调部分:

那么我们如何从数据库中获取数据呢?为此,Flask-SQLAlchemy 在Model类上提供了一个query属性。当您访问它时,您将在所有记录上返回一个新的查询对象。 然后,您可以使用filter()等方法筛选记录,然后再使用all()first()触发选择。如果要按主键,也可以使用get().

Model.query是 SQLAlchemyQuery类的(子类)的实例。

最新更新