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