I have a many-to-many relationship between Categories and Products as follows:
category_product = db.Table('category_product',
db.Column('category_id',
db.Integer,
db.ForeignKey('category.id')),
db.Column('product_id',
db.Integer,
db.ForeignKey('product.id')))
class Product(db.Model):
""" SQLAlchemy Product Model """
id = db.Column(db.Integer, primary_key=True)
sku = db.Column(db.String(10), unique=True, nullable=False)
name = db.Column(db.String(80), nullable=False)
categories = db.relationship('Category', secondary=category_product,
backref=db.backref('categories',
lazy='dynamic'))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Product {}>'.format(self.name)
class Category(db.Model):
""" SQLAlchemy Category Model """
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
products = db.relationship('Product', secondary=category_product,
backref=db.backref('products', lazy='dynamic'))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Category {}>'.format(self.name)
I am trying to get all the Product
objects in a given Category
, specified by category_id
:
products = db.session.query(Category).\
filter_by(id=category_id).\
products.\
all()
However, I get the following exception:
AttributeError: 'Query' object has no attribute 'products'
I'm probably missing something simple.
You cannot follow the filter_by with the attribute name 'products'. You first need to catch the results using all() or first(). Also since you are using Flask-SQLAlchemy, I suggest not using db.session.query(Category) and instead Category.query. So change this
products = db.session.query(Category).\
filter_by(id=category_id).\
products.\
all()
to
all_products = Category.query.\
filter_by(id=category_id).\
first().\
products
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With