3

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

3 回答 3

7

我终于找到了解决方案,其实很简单...... 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>
于 2012-12-13T18:07:22.823 回答
2

谁在乎。

myq = reduce(operator.and_, (myfunc(self.request.GET.getlist(param, None), param) for param in self.request.GET))
于 2012-12-13T16:36:25.283 回答
0

我真的不明白你想要做什么,但我认为这个问题在这种情况下实际上没有意义。&and|并不是Q对象上真正的布尔运算符:代码覆盖了__and__and__or__方法,以便它们将参数组合成一棵树,这就是 Django 在转换为 SQL 之前在内部表示查询的方式。

于 2012-12-13T11:32:19.313 回答