Django. Q objects dynamicaly generate

2019-06-11 02:56发布

问题:

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)