Always True Q object
Based on this answer we can make conditional argument passing
Obj.filter(
*( (Q(some_f1=some_v1),) if some else ()),
f1=v1,
f2=v2,
f3=v3,
f4=v4,
...
)
So, if some
is True
we add tuple (Q(some_f1=some_v1),)
to arguments list, in other case we add empty tuple ()
, also we need to wrap it in *()
, as always when we passing tuple of non-keyword args
Try this;
conditions = {'f1':f1,'f2':f2, 'f3':f3}
if some:
conditions['some_f1'] = some_v1
Obj.objects.filter(**conditions)
Here's one way to get an always true Q object:
always_true = ~Q(pk__in=[])
The ORM optimizer recognises that Q(pk__in=[])
always evaluates to False, and the ~
negates it to make it True.
as Alasdair answered in comment:
Obj.filter(
Q(some_f1=some_v1) if some else Q(),
f1=v1,
f2=v2,
f3=v3,
f4=v4,
...
)