问题
There is a filter for the model fields
queryset = queryset.filter(
Q(title__icontains=search_text) |
Q(description__icontains=search_text) |
Q(name_icontains=search_text)
)
How i can do generate block according to circumstances
Q(title__icontains=search_text) |
Q(description__icontains=search_text)|
Q(name_icontains=search_text)
For example, in one case it is necessary that the filter be such
Q(description__icontains=search_text) |
Q(name_icontains=search_text)
or
Q(title__icontains=search_text) |
Q(description__icontains=search_text) |
or
Q(title__icontains=search_text)
I could generate Q objects using a dictionary for example
search_text = 'somthing text'
fields_name = ['title', 'description', 'name']
queries = [ Q(**{field+'__icontains': search_text}) for field in fields_name]
but how this
[<Q: (AND: ('title__icontains': 'first'))>,
<Q: (AND: ('description__icontains': 'first'))>,
<Q: (AND: ('name__icontains': 'first'))>]
paste into filter and use OR separator
回答1:
You can do
>>>[Q(**{field +'__contains': search_text}) for field in fields_name]
Now if you want to do an OR
>>>import operator
>>>reduce(operator.or_, [Q(**{field+'__contains': search_text}) for field in fields_name])
Which is the same as
Q(title__icontains=search_text) |
Q(description__icontains=search_text)|
Q(name_icontains=search_text)
来源:https://stackoverflow.com/questions/43774659/django-q-objects-dynamicaly-generate