How to query many-to-many based on some constraint

2020-05-07 06:19发布

问题:

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.