Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for multiple values at once

Tags:

sqlalchemy

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
like image 763
phihag Avatar asked Mar 07 '13 09:03

phihag


People also ask

How do I SELECT multiple values in SQL query?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

How do I query multiple values from the same column in SQL?

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);

How do I run multiple queries at once?

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.

Can you SELECT multiple things in SQL?

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.


2 Answers

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.

like image 57
waitingkuo Avatar answered Oct 02 '22 23:10

waitingkuo


Use in_, like this:

q = meta.Session.query(cls)
q = q.filter(cls.id.in_([2,3,5,7,11]))
return q.all()
like image 20
phihag Avatar answered Oct 02 '22 23:10

phihag