动态访问Django模型字段python

时间:2013-11-04 17:30:41

标签: python django django-models

我有一个模型Level

class Level:
   level1_id = models.IntegerField()
   level2_id = models.IntegerField()
   level3_id = models.IntegerField()
   level4_id = models.IntegerField()
   level5_id = models.IntegerField()
   level6_id = models.IntegerField()
   level7_id = models.IntegerField()
   level_name = models.CharField()

我传递的是1-7范围内的整数id和AJAX中的名字。现在我想得到具有相应id和名称的levelX_id,X是id(1-7)。

这就是我的工作方式。

id = request.POST['id']
name = request.POST['name']  


if id == 1:
    level_name = Level.objects.all(level_name = name)[0].level1_id


if id == 2:
    level_name = Level.objects.all(level_name = name)[0].level2_id


if id == 3:
    level_name = Level.objects.all(level_name = name)[0].level3_id


if id == 4:
    level_name = Level.objects.all(level_name = name)[0].level4_id


if id == 5:
    level_name = Level.objects.all(level_name = name)[0].level5_id


if id == 6:
    level_name = Level.objects.all(level_name = name)[0].level6_id


if id == 7:
    level_name = Level.objects.all(level_name = name)[0].level7_id

我可以使它更通用吗?类似的东西。

level_X_id = "level"+id+"_id"
level_name = Level.objects.all(level_name = name)[0].level_X_id

1 个答案:

答案 0 :(得分:1)

我认为getattr就是你想要的。你可以这样做:

level_X_id = "level"+id+"_id"
level_name = getattr(Level.objects.all(level_name = name)[0], level_X_id)

希望这有帮助!