Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?

Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy?

SELECT * FROM foo WHERE foo.bar IN (1,2,3)

I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that doesn't use plain text?

select([foo], in(foo.c.bar, [1, 2, 3]))
select([foo]).in(foo.c.bar, [1, 2, 3])
like image 308
Mathias Avatar asked May 20 '09 11:05

Mathias


People also ask

What SQL does SQLAlchemy use?

Since SQLAlchemy relies on the DBAPI specification to interact with databases, the most common database management systems available are supported. PostgreSQL, MySQL, Oracle, Microsoft SQL Server, and SQLite are all examples of engines that we can use alongside with SQLAlchemy.

What is func in SQLAlchemy?

A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name.

Is SQLAlchemy the same as SQL?

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

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.


2 Answers

select([foo], foo.c.bar.in_([1, 2, 3]))

You can use the .in_() method with Columns or with Instrumented attributes. Both work.

It is mentioned here on SQLAlchemy's first tutorial.

like image 127
nosklo Avatar answered Sep 28 '22 12:09

nosklo


The .in_() operator now lives in the ColumnOperators class, documented @ http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_

Example usage:

ids_to_select = ["1", "2", "3"]
query(Model).filter(Model.id.in_(ids_to_select)).all()
like image 37
jaysee00 Avatar answered Sep 28 '22 11:09

jaysee00