8

I'd like to use the django.db.models.Q object in a way that the query term is coming from a variable.

What i'd like to achieve is identical to this:

q = Q(some_field__icontains='sth')
Obj.objects.filter(q)

, but the some_field value should come from a variable:

field_name='some_field'
q = Q('%s__icontains=sth' % field_name)
Obj.objects.filter(q)

, but this solution does not give me the correct result of course.

I also tried to use dictionary this way:

dt = {'%s__icontains' % field_name: 'sth'}
q = Q(**dt)
Obj.objects.filter(q)

, but this also fails on the result.

How could I use the Q object using variables as query term?

Thanks.

3
  • What do you mean with "fails on the result"? Commented Sep 28, 2020 at 16:18
  • It does not returns the correct (the expected) number of results. Actually it results 0. Commented Sep 28, 2020 at 16:21
  • Are you sure field_name is the some_field here? If you work with another field_name, of course the result can be different. Commented Sep 28, 2020 at 16:21

1 Answer 1

10

You can pass a 2-tuple to a Q object with the name of the fieldname(s) and lookups as first item, and the value as second item:

Obj.objects.filter(Q(('%s__icontains' % field_name, 'sth')))

this is probably the most convenient way. That being said the dictionary unpacking, although less elegant, should also work.

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately the dictionary way does not work, but your solution does! Thanks.
I am surprised that Obj.objects.filter(Q(**dt)) didn't work, but why? 🤔🤔
Unpacking definitely works. Worked for me.

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.