Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy Querying Many-to-Many

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.

like image 402
Mark Richman Avatar asked Oct 17 '13 19:10

Mark Richman


1 Answers

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
like image 75
codegeek Avatar answered Oct 21 '22 13:10

codegeek