I am getting
IndexError
tuple index out of range
the print in comment also gives ValueError malformed node or string: ['(300, 600)']
dict3={'diameter': {'attri': ['(300, 600)'], 'op': 'range'}}
result = Product.objects.all()
for key, value in dict3.items():
print(value['attri'])
print(value['op']) # print( ast.literal_eval(value['attri']))
if value['op'] is 'range':
result = result.filter(**{'attributes__{}__{}'.format(key, value['op']): ast.literal_eval(value['attri'])})
else:
result = result.filter(**{'attributes__{}__{}'.format(key, value['op']): value['attri']})
print(result)
dict3 = {'diameter': {'attri': ['(300, 600)'], 'op': 'range'}}
result = Product.objects.all()
for key, value in dict3.items():
print('attri:', ast.literal_eval(value['attri'][0]))
print('op:', value['op'])
if value['op'] == 'range':
rg = ast.literal_eval(value['attri'][0])
else:
rg = value['attri']
result = result.filter(**{'attributes__{}__{}'.format(key, value['op']): rg})
print(result)
Based on your comment, you want to generate a union , so every value in the list of 'attri'
is a condition, and the fact that one is triggered is sufficient.
We have to solve the problem that value['attri']
is a list of strings of tuples. We can do that by constructing a mapping over the elemenst. Perform literal_eval
on all of them, and then make a disjunction of the corresponding conditions. Something like:
from ast import literal_eval
from functools import reduce
from operator import or_
dict3 = {'diameter': {'attri': ['(300, 600)'], 'op': 'range'}}
result = Product.objects.all()
for key, value in dict3.items():
# use == instead of is
vls = value['attri']
if value['op'] 'range':
cond_name = 'attributes__{}__{}'.format(key, value['op'])
conditions =
result = result.filter()
This will produce the same disjunctive behavior for all other operators as well. Note however that the different items of dict3
will have conjunctive behavior, since you perform a chain of .filter(..)
actions, but you can use the same trick to make this disjunctive as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.