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])
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.
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.
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With