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.

cezar
  • 11,616
  • 6
  • 48
  • 84
9-bits
  • 10,395
  • 21
  • 61
  • 83

2 Answers2

84

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

nisc
  • 4,222
  • 4
  • 29
  • 34
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})
Sina Khelil
  • 2,001
  • 1
  • 18
  • 27
shafik
  • 6,098
  • 5
  • 32
  • 50
  • 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`? – Love Putin Not War Jun 11 '20 at 19:54