Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling filter with a variable for field name

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.

like image 746
9-bits Avatar asked Feb 03 '12 00:02

9-bits


2 Answers

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

like image 160
nisc Avatar answered Sep 24 '22 22:09

nisc


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}) 
like image 41
shafik Avatar answered Sep 23 '22 22:09

shafik