我想将字符串更改为变量。我在 Django 中有 7 个模型。
class Level1:
level1_id = models.IntegerField()
level1_name = models.CharField()
class Level2:
level2_id = models.IntegerField()
level2_name = models.CharField()
class Level3:
level3_id = models.IntegerField()
level3_name = models.CharField()
class Level4:
level4_id = models.IntegerField()
level4_name = models.CharField()
class Level5:
level5_id = models.IntegerField()
level5_name = models.CharField()
class Level6:
level6_id = models.IntegerField()
level6_name = models.CharField()
class Level7:
level7_id = models.IntegerField()
level1_name = models.CharField()
我通过 AJAX 请求传递了 1-7 范围内的整数 'level_id' 和 'name'。现在在我看来.py。
level_id = request.POST['level_id']
name = request.POST['name']
if level_id == 1:
level_name = Level1.objects.all(level1_name = name)
if level_id == 2:
level_name = Level2.objects.all(level2_name = name)
if level_id == 3:
level_name = Level3.objects.all(level3_name = name)
if level_id == 4:
level_name = Level4.objects.all(level4_name = name)
if level_id == 5:
level_name = Level5.objects.all(level5_name = name)
if level_id == 6:
level_name = Level6.objects.all(level6_name = name)
if level_id == 7:
level_name = Level7.objects.all(level7_name = name)
我可以减少所有if's
以使其更通用吗?就像是
dict = {"1":"Level1","2":"Level2","3":"Level3","4":"Level4","5":"Level5","6":"Level6","7":"Level7"}
level_name = dict[level_id].objects.all( dict[level_id]+"id" = name)