Search code examples
pythonflaskflask-sqlalchemyflask-restful

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


This is my full code of Flask application:

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)

As you can see I tried to extract data from Product model:

products = Product.all()

And I have got this error:

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'

Solution

  • You forgot the use the .query attribute to access the query object; .all() is a method on that object:

    products = Product.query.all()
    

    From the Querying Reconds section of the Flask-SQLAchemy documentation:

    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 is an instance of (a subclass of) the SQLAlchemy Query class.