Django的。动态生成Q对象

时间:2017-05-04 05:38:34

标签: python django django-q

模型字段有一个过滤器

queryset = queryset.filter(
            Q(title__icontains=search_text) |
            Q(description__icontains=search_text) |
            Q(name_icontains=search_text)
        )

我如何根据情况生成块

  

Q(title__icontains = search_text)|
                  Q(= description__icontains SEARCH_TEXT)|
                  Q(name_icontains = search_text)

例如,在一种情况下,过滤器必须是这样的

  

Q(description__icontains = search_text)|
                  Q(name_icontains = search_text)

  

Q(title__icontains = search_text)|
                  Q(description__icontains = search_text)|

  

Q(title__icontains = search_text)

我可以使用字典生成Q对象 例如

search_text = 'somthing text'
fields_name = ['title', 'description', 'name']

 queries = [ Q(**{field+'__icontains': search_text}) for field in fields_name]  

但是如何

[<Q: (AND: ('title__icontains': 'first'))>, <Q: (AND: ('description__icontains': 'first'))>, <Q: (AND: ('name__icontains': 'first'))>]

粘贴到过滤器并使用OR分隔符

1 个答案:

答案 0 :(得分:1)

你可以做到

>>>[Q(**{field +'__contains': search_text}) for field in fields_name]

现在,如果你想进行OR

>>>import operator
>>>reduce(operator.or_, [Q(**{field+'__contains': search_text}) for field in fields_name])

相同
Q(title__icontains=search_text) |
Q(description__icontains=search_text)|
Q(name_icontains=search_text)