我想改變字符串作爲變量。 我在Django有7個模型。如何將字符串更改爲python django中的變量?
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請求傳遞一個整數'level_id'在1-7範圍內和'名稱'。現在在我的views.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
使其更加generc。喜歡的東西
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)
您而重新考慮你的模型。看來您可以使用單個模型實現相同的功能。 – Yossi