In SQL, I can get a set of rows like this:
SELECT * FROM table WHERE id in (2,3,5,7,11);
How does the equivalent sqlalchemy query look? cls.id in [2,3,5,7,11]
evaluates to False
, so this code:
q = meta.Session.query(cls)
q = q.filter(cls.id in [2,3,5,7,11])
return q.all()
fails with an exception:
File "foo.py", line 1234, in findall_by_ids
q = q.filter(cls.id in [2,3,5,7,11])
File "<string>", line 1, in <lambda>
File "/eggs/sqlalchemy/orm/query.py", line 50, in generate
fn(self, *args[1:], **kw)
File "/eggs/sqlalchemy/orm/query.py", line 1177, in filter
"filter() argument must be of type "
ArgumentError: filter() argument must be of type sqlalchemy.sql.ClauseElement
or string
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);
To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
Use in_
q.filter(cls.id.in_([2, 3, 5, 7, 11]))
Your interpreter said:
ArgumentError: filter() argument must be of type sqlalchemy.sql.ClauseElement
or string
Those operators have been overwritten and will return what filter need, you can take a look at sqlalchemy.sql.operators
. The reason that cls.id in [2, 3, 5, 7, 1]
doesn't work is because that in
is the operator of [2, 3, 5, 7, 1], it'll return True
or False
.
Use in_
, like this:
q = meta.Session.query(cls)
q = q.filter(cls.id.in_([2,3,5,7,11]))
return q.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