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)
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.