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?
in
db_session.query(Star).filter(Star.star_type in ('Nova', 'Planet'))
The query returns empty.
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.
You can do it like this:
db_session.query(Star).filter(Star.star_type.in_(['Nova', 'Planet']))
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'])
)
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