Conditionally Filtering in SQLAlchemy

Try collecting your queries into a list, and then use the * operator when you call filter:

queries = [X.y == 'a']
if b:
    queries.append(X.z == 'b')
q.filter(*queries)

And BTW I don’t understand why you think chaining two filters would change your query, it would correspond to X.y = a AND X.z = b like when you use filter(X.y == 'a', X.z == 'b').

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)