【问题标题】:AttributeError: type object 'Product' has no attribute 'all' Flask?AttributeError:类型对象'Product'没有属性'all'Flask?
【发布时间】:2018-01-12 05:43:04
【问题描述】:

这是我的 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'

【问题讨论】:

  • 我是Product.query.all()

标签: python flask flask-sqlalchemy flask-restful


【解决方案1】:

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

products = Product.query.all()

来自 Flask-SQLAchemy 文档的Querying Reconds section

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

Model.query 是(a subclass of)SQLAlchemy Query class 的一个实例。

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2019-06-08
    • 2022-01-12
    • 2016-11-18
    相关资源
    最近更新 更多