简体   繁体   English

Flask-SQLAlchemy查询多对多

[英]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 : 我试图获取由category_id指定的给定Category中的所有Product对象:

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'. 您不能使用属性名称“products”跟随filter_by。 You first need to catch the results using all() or first(). 首先需要使用all()或first()来捕获结果。 Also since you are using Flask-SQLAlchemy, I suggest not using db.session.query(Category) and instead Category.query. 此外,由于您使用的是Flask-SQLAlchemy,我建议不要使用db.session.query(Category)而是使用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

For someone who need... 对于需要......的人

You can use .any() 你可以使用.any()

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

I'm not test the query. 我不测试查询。 But I think it's work... Happy coding... 但我认为这是有效的......快乐的编码......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM