SQLAlchemy: Check if a given value is in a list

17k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

You can do it like this:

db_session.query(Star).filter(Star.star_type.in_(['Nova', 'Planet']))
0
On

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'])
)