How to build complex django query as a string

流过昼夜 提交于 2019-12-06 05:00:28

Construct a Q object and use it in filter():

from viewer.models import Model1
from django.db.models import Q

list1 = [
    {'nut' : 'peanut', 'jam' : 'blueberry'},
    {'nut' : 'almond', 'jam' : 'strawberry'}
]

q = Q()
for x in list1:
    q.add(Q(**x), Q.OR)

query_results = Model1.objects.filter(q)

Or, you can use operator.or_ to join the list of Q objects:

import operator
from viewer.models import Model1
from django.db.models import Q

list1 = [
    {'nut' : 'peanut', 'jam' : 'blueberry'},
    {'nut' : 'almond', 'jam' : 'strawberry'}
]

query_results = Model1.objects.filter(reduce(operator.or_, 
                                             [Q(**x) for x in list1]))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!