Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 574
wonzbak Avatar asked Dec 22 '11 11:12

wonzbak


People also ask

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

How do I SELECT in SQLAlchemy?

The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.

How does the querying work with SQLAlchemy?

All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.


1 Answers

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.

like image 175
Simon Avatar answered Sep 18 '22 18:09

Simon