Flask-SQLAlchemy Many-to-Many Query

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 try to get all the objects Productin the given Category, specified 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 probably miss something simple.

+5
source share
2 answers

You cannot follow filter_by with the attribute name 'products'. First you need to catch the results using all () or first (). Also, since you are using Flask-SQLAlchemy, I suggest not using db.session.query (Category), but instead of Category.query. Therefore 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
+4

, ...

.any()

product = Product.query.filter(Category.products.any(id=cat_id)).all()

. , ... ...

0

All Articles