gpt4 book ai didi

python - python 动态访问 Django 模型字段

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:45 24 4
gpt4 key购买 nike

我有一个模型级别

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 的名称。现在我想获取 levelX_id 及其各自的 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

最佳答案

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

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

希望这有帮助!

关于python - python 动态访问 Django 模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com