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

后端 未结 1 1598
闹比i
闹比i 2021-01-29 05:17

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)

相关标签:
1条回答
  • 2021-01-29 06:17

    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.

    0 讨论(0)
提交回复
热议问题