模型字段有一个过滤器
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分隔符
答案 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)