AttributeError: type object 'Product' has no attribute 'all' Flask?

AttributeError: type object 'Product' has no attribute 'all' Flask?

这是我的 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:\Projects\Dist\backend\index.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 文档的Querying Reconds section

So how do we get data back out of our database? For this purpose Flask-SQLAlchemy provides a query attribute on your Model class. When you access it you will get back a new query object over all records. You can then use methods like filter() to filter the records before you fire the select with all() or first(). If you want to go by primary key you can also use get().

Model.query 是 (a subclass of) the SQLAlchemy Query class.

的实例