41

Is there a way to call filter on a queryset where one of the fieldnames is a variable?

For example I have something like:

models.py

class Playlist(models.Model):
    video = ...

views.py

field_name = 'video'
Playlist.objects.filter(field_name=v)

Which of course results in an error that field_name is not an attribute upon which Playlist can be filtered.

1
  • 2
    Common, I need Internet points!
    – nisc
    Feb 3, 2012 at 13:08

2 Answers 2

85

Playlist.objects.filter(**{field_name: v})

2
  • 1
    how do i use __icontains with the field_name? it gives an error
    – Naveen
    Feb 5, 2019 at 12:14
  • 2
    Try with: field_name = 'video__icontains' , it worked for me
    – gmarsi
    Apr 13, 2020 at 11:21
10

To use field name string with icontains.

Try this

field_name = 'video'
field_name_icontains = field_name + '__icontains'
Playlist.objects.filter(**{field_name_icontains: v})
1
  • Is there a way to pass the model name as a variable in a queryset? eg. in a queryset like var_duty_cond = DutyHdr.objects.get(duty_hdr_component = varMainDutyType).duty_main, how may I pass a variable varDutyHdr in place of model DutyHdr? Jun 11, 2020 at 19:54

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.