Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 386
James Lam Avatar asked Jun 26 '15 02:06

James Lam


1 Answers

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

like image 112
satoru Avatar answered Sep 23 '22 03:09

satoru