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>