Django. Q objects dynamicaly generate

折月煮酒 提交于 2019-12-23 04:59:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!