如何将复杂的django查询构建为字符串

时间:2014-06-10 13:19:31

标签: django models django-queryset

我正在动态生成一个包含多个参数的查询字符串。我想在我的字符串中包含对象名称(' nut',' jam')。查询必须是" OR"查询。我的代码在下面,我得到如下所示的错误。解决方案hereherehere对我无效。

from viewer.models import Model1
from django.db.models import Q
list1 = [
    {'nut' : 'peanut', 'jam' : 'blueberry'},
    {'nut' : 'almond', 'jam' : 'strawberry'}
]
query_string = ""
for x in list1:
    if len(query_string) == 0:
        query_string = "Q(nut='%s', jam='%s')" % (x["nut"], x["jam"])
    else:
        query_string = "%s | Q(nut='%s', jam='%s')" % (query_string, x["nut"], x["jam"])
print query_string # correctly prints Q(nut='peanut', jam='blueberry') | Q(nut='almond', jam='strawberry')
query_results = Model1.objects.filter(query_string)

Error: 
#truncated
File "/Library/Python/2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/manager.py", line 155, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/query.py", line 669, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/query.py", line 687, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Library/Python/2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
  File "/Library/Python/2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/sql/query.py", line 1066, in add_filter
arg, value = filter_expr
ValueError: too many values to unpack

1 个答案:

答案 0 :(得分:3)

构建Q对象并在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)

或者,您可以使用operator.or_加入Q个对象列表:

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]))