Conditionally filtering in SQLAlchemy

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

For example, imagine I have the following:

 q = session.query(X) if a: q.filter(Xy == 'a') elif b: q.filter(Xy == 'a', Xz == 'b') elif c: q.filter(Xy == 'a', Xp == 'd') 

Is there any way to say just add

Xz == 'b' if b

without reading (Xy == 'a') in each filter.

It seems like I could do

q.filter(Xy == 'a').filter(Xy == 'b')

but this changes the running query.

+5
source share
1 answer

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

 queries = [Xy == 'a'] if b: queries.append(Xz == 'b') q.filter(*queries) 

And BTW I don’t understand why you think that a chain of two filter will change your request, it will correspond to Xy = a AND Xz = b as when using filter(Xy == 'a', Xz == 'b') .

+5
source

All Articles