django.db.models.Q操作的对象的中性元素是什么?我想生成一个具有以下功能的筛选器:

MyModel.objects.filter(myfunc(args)) where myfunc should give something like: "Q(foo) | Q(bar) | ... | False"

但我不知道什么是|对象。同样,我需要中性元素来进行False操作(Q)。。。
下面是这样一个函数的示例:
# 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>

最佳答案

我终于找到了解决办法,其实很简单。。。Q对象的“中性元素”与操作“|”和“&”的“中性元素”是相同的:“Q()”
我现在有一个动态过滤器,可以匹配我的模板中想要的一切。。。

# Models
class MyModel(models.Model):
    myfield1 = models.CharField(max_length=30)
    myfield2 = models.CharField(max_length=30)
    myinteger3 = models.IntegerField(blank=True, null=True)



# 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()) # Q() is the neutral element of operation "|" for Q objects
            return myfuncr(query_object_list)

        myq = Q() # Q() is 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 }}&myinteger3__gte={{ myvar3 }}'>foobar</a>

<a href='{% url myview %}?myinteger3__gte={{ myvar4 }}'>{{ myvar4 }}</a>

10-04 10:31