“|”的中性元素和“&” django.db.models.Q对象的操作?

时间:2012-12-13 11:09:22

标签: python django django-queryset

django.db.models.Q操作的|个对象的中性元素是什么?我想生成一个带函数的过滤器:

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

但我不知道False个对象的Q是什么。同样,我需要&操作的中性元素(True)...

以下是此类功能的示例:

# 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>

3 个答案:

答案 0 :(得分:5)

我终于找到了解决方案,其实很简单...... Q对象的“中性元素”,对于操作“|”来说是相同的和“&amp;”是:“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>

答案 1 :(得分:2)

谁在乎。

myq = reduce(operator.and_, (myfunc(self.request.GET.getlist(param, None), param) for param in self.request.GET))

答案 2 :(得分:0)

我真的不明白你想要做什么,但我不认为这个问题在这方面确实有意义。 &|Q个对象上不是真正的布尔运算符:code会覆盖__and____or__方法,以便它们合并参数在转换为SQL之前,Django在内部表示查询。