Более элегантное решение @ vdmit11, использующее кортежи SQL:
from sqlalchemy import inspect, tuple_
# List of Column objects of the primary key
pk_columns = inspect(models.Object).primary_key
pk_names = [col.key for col in pk_columns]
# Build the condition: (primary-key-tuple) IN (....)
condition = tuple_(*pk_columns).in_(
# Every object is represented by its primary key tuple
tuple(entity_dict[pk_field] for pk_field in pk_names)
for entity_dict in primary_keys
)
instances = ssn.query(models.Object).filter(condition).all()
. Он сгенерирует запрос, который выглядит следующим образом:
SELECT *
FROM users
WHERE (uid, login) IN ((1, 'vdmit11'), (2, 'kolypto'));