gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:49:35 27 4
gpt4 key购买 nike

我正在动态生成具有多个参数的查询字符串。我试图在我的字符串中包含对象名称('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

最佳答案

构造一个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]))

关于django - 如何将复杂的 Django 查询构建为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24142112/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com