James Lam
James Lam

Reputation: 1279

Conditionally Filtering in SQLAlchemy

Is there a way to conditionally add filter arguments to a query in the SQL Alchemy ORM?

For example imagine, I have the following:

q = session.query(X)
if a:
 q.filter(X.y == 'a')
elif b:
 q.filter(X.y == 'a', X.z == 'b')
elif c:
 q.filter(X.y == 'a', X.p == 'd') 

Is there a way to say just add

X.z == 'b' if b

without having to readd (X.y == 'a') in every filter.

It seems that I could do

q.filter(X.y == 'a').filter(X.y == 'b')

but this changes the query that is being performed.

Upvotes: 45

Views: 24377

Answers (1)

satoru
satoru

Reputation: 33235

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

Upvotes: 74

Related Questions