Calling filter with a variable for field name

半城伤御伤魂 提交于 2019-12-20 11:15:08

问题


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:


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




回答2:


To use field name string with icontains.

Try this

field_name = 'video'
field_name_icontains = field_name + '__icontains'
Playlist.objects.filter(**{field_name: v})


来源:https://stackoverflow.com/questions/9122169/calling-filter-with-a-variable-for-field-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!