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.
field_name
is thesome_field
here? If you work with anotherfield_name
, of course the result can be different. – Audriaaudrie