Access Django model's fields using a string instead of dot syntax?

前端 未结 4 1450
青春惊慌失措
青春惊慌失措 2020-12-13 05:49

In Django, I can do this:

test = Test.objects.get(id=1)
test.name

I want to be able to access the properties using dynamically generated st

4条回答
  •  清歌不尽
    2020-12-13 06:19

    Assuming name is an attribute on your instance test getattr(test, 'name') should return the corresponding value. Or test.__dict__['name'].

    You can read more about getattr() here: http://effbot.org/zone/python-getattr.htm

提交回复
热议问题