姜戈。 Q对象动态生成
Django. Q objects dynamicaly generate
模型字段有一个过滤器
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 分隔符
你可以做到
>>>[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)
模型字段有一个过滤器
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 分隔符
你可以做到
>>>[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)