4 ms·
I use this pattern in Django and I feel without ORM or query builder this will need 4 raw queries. ``` results = Foo.objects()... if a: results = results.fil
by aitchnyu 5y ago
I use this pattern in Django and I feel without ORM or query builder this will need 4 raw queries.
```
results = Foo.objects()...
if a:
results = results.filter(a=a)
if b:
results = results.filter(a=b)
```
- EdwardDiego 5y agoselect * from foo where case when :filter_on_a and not :filter_on_b then a=:a when :filter_on_b and not :filter_on_a then b=:b when :filter_on_a and :filter_on_b then a=:a and b=:b else true end Should preserve all your semantics. I can't remember if Python DBAPI handles named parameters, so let's pretend it does and the colon-prefixed parameters are in the right syntax. cur.execute("above query", filter_on_a=bool(a), filter_on_b=bool(b), a=a, b=b) Whether the more complex SQL is worth it really depends on your use case.