选择仅具有字符串名称的字段

时间:2013-03-26 16:50:36

标签: python django

我的模型看起来像这样:

class WeekOne(models.Model):
    # Required benchmarks for given exercises
    squatBenchmark = 1000
    lungeBenchmark = 250
    stairDaysCountBenchmark = 3

    totalGoals = 4

    squats = models.PositiveIntegerField(default=0)
    lunges = models.PositiveIntegerField(default=0)
    skipStairs = models.BooleanField(default=False)
    stairDaysCount = models.PositiveSmallIntegerField(default=0)
    # Running count of benchmarks met.
    completeCount = models.PositiveSmallIntegerField(default=0)
    # Set to true if benchmarks reached. 
    weekOneComplete = models.BooleanField(default=False)

我想访问字段'squats',即在变量赋值amount = user.week_one.squats中,但由于视图和模板的工作方式,我无法访问对深蹲字段的引用,我只有一个字符串squats。有没有办法使用这个字符串来访问该字段?

1 个答案:

答案 0 :(得分:4)

这是getattr的用途:

amount = getattr(user.week_one, 'squats')