使用字符串而不是点语法访问 Django 模型的字段?

在姜戈,我可以这样做:

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

我希望能够使用动态生成的字符串访问属性,如下所示:

test['name']

或者其他任何使用字符串的语法,我试过了

test._meta.get_field_by_name('name')

但它返回的是字段本身,而不是值。

有什么想法吗?

40957 次浏览

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

In Python, you can normally access values within an object that has a dict method.

Let's say you have this class:

class Dog(object):
def __init___(self, color):
self.color = color

And then I instantiate it:

dog = Dog('brown')

So i can see the color by doing:

print dog.color

I can also see the color by doing:

print dog.__dict__['color']

I can set the color:

print dog.__dict__['color'] = 'green'


print dog.color


>>>green

You can use python's built in getattr() function:

getattr(test, 'name')

Other answers still stand, but now you can do this using Django's _meta.get_field().

test._meta.get_field('name')

Note that the Model _meta API has begun its official support and documentation as of 1.8, but has been distributed and used in prior versions before its official documentation.