Reputation: 20137
I need to prepare filter with dynamic fields.. I don't know the field name so i need to give it dynamically. here what i tried so far,
gen_query = reduce(operator.or_, (Q(eval('%s=i' % (field, i))) for i in request.query_params.get(field).split(',')))
but it raising syntax error!
i am using, eval(field_name as string)
still i am getting an error..
how to achieve this?
i want to do django filtering with q objects with dynamic fields
Upvotes: 1
Views: 1467
Reputation: 7376
You can create dict with parameters and unpack it in Q constructor:
gen_query = reduce(operator.or_, (Q(**{field: i}) for i in request.query_params.get(field).split(',')))
Upvotes: 8
Reputation: 9431
Could you use Q('{}={}'.format(field, i))
if you need string formatting?
Upvotes: 0