Skip to content Skip to sidebar Skip to footer

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 SQLAlc

Solution 1:

You can do it like this:

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

Solution 2:

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

Post a Comment for "Sqlalchemy: Check If A Given Value Is In A List"