What is the neutral element for django.db.models.Q objects for | operation? I’d like to generate a filter with a function:
MyModel.objects.filter(myfunc(args)) where myfunc should give something like: "Q(foo) | Q(bar) | ... | False"
but I don’t know what is False for Q objects. Similarly, I would need the neutral element for & operation (True)…
Here is an example of such a function:
# Models
class MyModel(models.Model):
myfield1 = models.CharField(max_length=30)
myfield2 = models.CharField(max_length=30)
# Views
class MyView(views.View):
model = MyModel
def get_queryset(self):
def myfunc(query_object_list, param):
myfuncr = lambda l: ((myfuncr(l[1:]) | Q(**{ param: l[0] })) if l else Q(False)) # "Q(False)" would be the neutral element of operation "|" for Q objects
return myfuncr(query_object_list)
myq = Q(True) # "Q(True)" would be the neutral element of operation "&" for Q objects
for param in self.request.GET:
myq &= myfunc(self.request.GET.getlist(param, None), param)
return MyModel.objects.filter(myq)
# Template
<a href='{% url myview %}?myfield1__iexact={{ myvar1 }}&myfield2__iexact={{ myvar2 }}'>foobar</a>
I finally found the solution, which was in fact pretty simple… the “neutral element” for Q objects, which is the same for operations “|” and “&” is: “Q()”
I now have a dynamic filter which can match everything I want in my templates…