How to query many-to-many based on some constraints in flask sqlalchemy?

假装没事ソ 提交于 2019-12-20 06:23:43

问题


If I have a User and Item model, and they have a many-to-many association with each other, how do I build a query that returns:

(1) All items that belong to any user named 'Bob'

I tried:

Item.query.filter(User.name == 'Bob')

Which returns all items regardless of the user's name (incorrect)

(2) All items that have the name 'shark' and belong to any user named 'Bob'

I tried:

Item.query.filter(User.name == 'Bob' & Item.name == 'shark')

Same as above, but only returns items named 'shark' regardless of the user's name. (incorrect)

My model definitions:

association_table = Table('items_users',
    Column('itemid', Integer, ForeignKey('item.id'), primary_key=True),
    Column('userid', Integer, ForeignKey('user.id'), primary_key=True)
)

class Item(Model):
    # other fields...

    # many to many association
    users = relationship('User', secondary=association_table, lazy='dynamic', backref=backref('items', lazy='dynamic'))

class User(Model):
    # other fields...

What would be appropriate syntax for two queries?


回答1:


You need to join the tables you will query, so that filtering one will filter the combined row associated with the other. Since you have defined a relationship between the two models, you can join on it rather than specifying a join condition manually.

Item.query.join(Item.users).filter(User.name == 'bob')
Item.query.join(Item.users).filter(User.name == 'bob', Item.name == 'shark')

Working with relationships and joins is covered in the comprehensive tutorial in the SQLAlchemy docs.



来源:https://stackoverflow.com/questions/32575502/how-to-query-many-to-many-based-on-some-constraints-in-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!