djangodjango-ormdjango-q

Always True Q object


I want to create some part of Django ORM filter query dinamicly, now I can do:

if some:
   Obj.filter(
       some_f1=some_v1,
       f1=v1,
       f2=v2,
       f3=v3,
       f4=v4,
       ...
   )
else:
   Obj.filter(
       f1=v1,
       f2=v2,
       f3=v3,
       f4=v4,
       ...
   )

I want something without code duplicate like this:

Obj.filter(
    Q(some_f1=some_v1) if some else True,  # what to use instead of True?
    f1=v1,
    f2=v2,
    f3=v3,
    f4=v4,
    ...
)

Solution

  • 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.