1

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

2 Answers 2

8

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(',')))
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

this is filter query... i think there is no meaning in it... your code will just do concatenation as i did.. its just an another method
Not working. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.