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:
Solution 1:
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.
Post a Comment for "SQLAlchemy - Adding OR Condition With Different Filter"