我有一个带有选择列表/正整数字段的模型类。
class AchievementDetails(models.Model, FillableModelWithLanguageVersion):
ACADEMIC_ACHIEVEMENT = 1
COMMERCIAL_ACHIEVEMENT = 2
PERSONAL_ACHIEVEMENT = 3
PROFESSIONAL_ACHIEVEMENT = 4
SPORTING_ACHIEVEMENT = 5
OTHER_ACHIEVEMENT_TYPE = 6
ACHIEVEMENT_TYPES = (
(ACADEMIC_ACHIEVEMENT, _('Academic Details')),
(COMMERCIAL_ACHIEVEMENT, _('Commercial Achievement')),
(PERSONAL_ACHIEVEMENT, _('Personal Achievement')),
(PROFESSIONAL_ACHIEVEMENT, _('Professional Achievement')),
(SPORTING_ACHIEVEMENT, _('Sporting Achievement')),
(OTHER_ACHIEVEMENT_TYPE, _('Other Achievement Type')),
)
....
achievement_type = models.PositiveIntegerField(choices=ACHIEVEMENT_TYPES)
....
在我的views.py中,我试图显示成就类型的选定文本。例如:学业成就
目前我只能显示所选的数值。例如:1
以下是我在views.py中的代码:
def achievement_details(request):
....
for ad in achievement_details:
ad.achievement_type_as_text = ad.achievement_type
....
返回ACHIEVEMENT_TYPES所选文字的正确代码是什么?
答案 0 :(得分:1)
这就是答案:
https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display
因此,对于我的示例,语法将是:
def achievement_details(request):
....
for ad in achievement_details:
ad.achievement_type_as_text = ad.get_achievement_type_dispay()
....
我希望这可以帮助别人。
答案 1 :(得分:0)
由于你有一个元组列表,你想使用类似下面的
ACHIEVEMENT_TYPES = (
(ACADEMIC_ACHIEVEMENT, 'Academic Details'),
(COMMERCIAL_ACHIEVEMENT, 'Commercial Achievement'),
(PERSONAL_ACHIEVEMENT, 'Personal Achievement'),
(PROFESSIONAL_ACHIEVEMENT, 'Professional Achievement'),
(SPORTING_ACHIEVEMENT, 'Sporting Achievement'),
(OTHER_ACHIEVEMENT_TYPE, 'Other Achievement Type'),
)
result = [item for item in ACHIEVEMENT_TYPES if item[0] == ad.achievement_type]
ad.achievement_type_as_text = result[1]