Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Check if a given value is in a list

The problem

In PostgreSQL, checking whether a field is in a given list is done using the IN operator:

SELECT * FROM stars WHERE star_type IN ('Nova', 'Planet');

What is the SQLAlchemy equivalent for an IN SQL query?

What have I tried

Python's in

db_session.query(Star).filter(Star.star_type in ('Nova', 'Planet'))

The query returns empty.

SQLAlchemy's or_

db_session.query(Star).\
           filter(or_(
                      Star.star_type == 'Nova', 
                      Star.star_type == 'Planet'
           ))

This query returns the right result, but it is not elegant and hard to expand.

like image 535
Adam Matan Avatar asked Jun 10 '15 11:06

Adam Matan


2 Answers

You can do it like this:

db_session.query(Star).filter(Star.star_type.in_(['Nova', 'Planet']))
like image 92
plaes Avatar answered Nov 13 '22 20:11

plaes


A bad way of solving this problem (which I used successfully before finding accepted answer) is to use list comprehension:

db_session.query(Star).filter(
    or_(*[Star.star_type == x for x in ['Nova', 'Planet'])
)
like image 37
Yaakov Bressler Avatar answered Nov 13 '22 20:11

Yaakov Bressler