2014-01-20 59 views
1

我想知道是否有可能从字符串访问djangomodel中的字段。 Letme给你举个例子:django访问模型字段的字符串

类:

class Resource(models.Model): 
    town = models.ForeignKey(Town, unique=True) 

    coin = models.IntegerField() 
    wood = models.IntegerField() 
    iron = models.IntegerField() 
    grain = models.IntegerField() 
    stone = models.IntegerField() 

现在我在其他地方的代码,我想进入电影场这样

example="coin" 
resources = Resource.objects.get(town="some town"): 
resources.example 

我知道resources.example不工作,我想知道是否有办法实现这一目标?

随着亲切的问候, 汉斯·德容

回答

5

可以按名称使用getattr内置函数

example="coin" 
resources = Resource.objects.get(town="some town"): 
getattr(resources, example) 
访问任何对象的属性在Python