使用OR逻辑运算符组合任意数量或Q个对象的过滤器 [英] Filter with arbitrary number or Q objects combined by OR logical operator
问题描述
Django 1.10.1
搜索表单。用户插入用空格分隔的单词。
必须在标题字段中查找具有 ANY 个单词的对象。
Search form. The user inserts words separated by spaces. Necessary to find objects with ANY of these words in the title field.
我打算使用类似这样的东西:
I'm planning to use something like this:
Article.objects.filter(
Q(title__icontains="table") | Q(title__icontains="helm")
)
我可以轻松地制作Q对象:q = Q(title__icontains = table
I can make Q objects easily: q = Q(title__icontains="table").
但是障碍是如何将参数传递给filter方法。
But the obstacle is how to pass arguments to the filter method.
https://docs.djangoproject.com/en/1.10/topics/db/queries/
语法为 filter(** kwargs)。
循环,我可以准备像这样的字典:
With a loop I can prepare a dictionary like this :
q_objects = {"1": Q(title__icontains="table"), "2": Q(title__icontains="glasses")}
但是问题在于 > | 。
如何将其传递给filter方法对我来说还是一个谜。换句话说,我无法使用OR逻辑运算符构建过滤器。
But the problem is with that "|".
How to pass it to the filter method is a mystery to me. In other words I fail to build a filter with OR logical operator.
您能帮我吗?
推荐答案
您可以执行以下操作:
queryset = MyModel.objects.all()
queries = ['table, helm']
filter_ = 'title__icontains'
queryset.filter(reduce(lambda q1,q2: q1|q2, [Q(**{filter_: q}) for q in queries], Q()))
#This will build a QuerySet similar to this one:
queryset.filter(Q(title__icontains='table')|Q(title__icontains='helm'))
这篇关于使用OR逻辑运算符组合任意数量或Q个对象的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!