41

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.

James Lam
  • 1,179
  • 1
  • 15
  • 21

1 Answers1

67

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

satoru
  • 31,822
  • 31
  • 91
  • 141
  • 2
    This is PERFECT! I'm using this * operator to conditionally pass in multiple criteria into an or_ function – Buzzrick Jan 14 '16 at 02:23