postgresqlsqlalchemycompound-key

SQLAlchemy: Querying compound primary key with `IN` operator


Assuming a table foo with compound primary key (a,b), How I can generate following sql query with SQLAlchemy (postgresql dialect)?

SELECT * FROM foo WHERE (a,b) IN ((1,2), (2,3));

Solution

  • Here is the answer:

    from sqlalchemy.sql.expression import Tuple
    session.query(Foo).filter(Tuple(Foo.a, Foo.b).in_([(1,2), (3,4)])).all()