0

我想将字符串更改为变量。我在 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)
4

1 回答 1

2

你可以在这里使用djangoget_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()

这样你就知道它指的是哪个级别。

甚至更好

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

并摆脱Level1, Level2, ... 这更具可扩展性

于 2013-11-03T17:53:43.283 回答