I am dynamically generating a query string with multiple parameters. I am trying to include the object names ('nut', 'jam') in my string. The query has to be an "OR" query. My code is below and I get the error shown below. The solutions here, here, and here did not work for me.
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