2013-11-03 66 views
0

我想改變字符串作爲變量。 我在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) 
+2

您而重新考慮你的模型。看來您可以使用單個模型實現相同的功能。 – Yossi

回答

2

您可以使用django get_model,你的優勢在這裏:

from django.db.models.loading import get_model 

level_id = request.POST['level_id'] 
name = request.POST['name'] 
model = get_model('app_name', 'Level%s' % level_id) #replace app_name with the app this model resides in. 

params = {"level%s_name" % level_id: name} 
level_name = model.objects.filter(**params) 

我不知道爲什麼你

class Level1(): 
    level1_name = CharField() 

你可以只讓

class Level1(): 
    level_name = CharField() 

這樣你就知道了wh它指的是它的水平。

更妙

class Level() 
    level_name = CharField() 
    level_id = IntegerField() 

,擺脫Level1Level2,...這是更擴展

+0

這個app_name指的是保存我的models.py的應用程序嗎? –

+0

當然是的。 – karthikr

相關問題