pythonsqlalchemyin-clause

SQLAlchemy IN clause


I'm trying to do this query in sqlalchemy

SELECT id, name FROM user WHERE id IN (123, 456)

I would like to bind the list [123, 456] at execution time.


Solution

  • How about

    session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()
    

    edit: Without the ORM, it would be

    session.execute(
        select(
            [MyUserTable.c.id, MyUserTable.c.name], 
            MyUserTable.c.id.in_((123, 456))
        )
    ).fetchall()
    

    select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.