Querying from list of related in SQLalchemy and Flask

You can also use the generator with or_:

from sqlalchemy.sql import or_
people = Person.query.filter().limit(3)
cond = or_(*[User.person == person for person in people])
User.query.filter(cond).all()

This can be useful when you try to request records with filter of objects that have already been received, such as statuses.


As the error message helpfully tells you, you need to use in_ against the foreign keys instead:

User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all()

Since you're going to query for both anyway, might be better to do a joined load and then get the people using Python:

people = Person.query.join(Person.user).options(db.contains_eager(Person.user)).limit(3).all()
users = [p.user for p in people]