Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

django filtering with q objects with dynamic fields

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

Answers (2)

Dima  Kudosh
Dima Kudosh

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

Nik
Nik

Reputation: 9431

Could you use Q('{}={}'.format(field, i)) if you need string formatting?

Upvotes: 0

Related Questions