Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - adding OR condition with different filter

For the SQL statement, I want to do an OR filter only if the input variable is not None.

E.g

# input variable
var_1 = "apple"
var_2 = "pear"

query = session.query(Table)
if var_1:
    query = query.filter(or_(Table.field1 == var_1))
if var_2:
    query = query.filter(or_(Table.field2 == var_2))

But this is not possible. The 2nd query became an AND statement instead.

I don't want to do this because I don't want to compare an input variable if it's null or empty string.

query = query.filter(or_(Table.field1 == var_1, Table.field2 == var_2))

How do I solve this?

like image 310
chrizonline Avatar asked Jul 11 '26 05:07

chrizonline


1 Answers

You can dynamically construct the "OR" part:

query = session.query(Table)

conditions = []
if abc:
    conditions.append(Table.field1 == abc)
if def:
    conditions.append(Table.field2 == def)

query = query.filter(or_(*conditions))

Also note that the def is a reserved word in Python, consider renaming this variable.

like image 191
alecxe Avatar answered Jul 13 '26 18:07

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!