
本文档旨在解决 Django 模型中使用 `CharField` 和 `choices` 属性时,如何在模板中显示选项的完整名称,而不是存储在数据库中的缩写值。通过 `get_FIELD_display()` 方法,可以轻松地在模板中呈现更具可读性的选项名称。
在 Django 开发中,我们经常需要在模型中使用下拉选择框来限制用户输入。为了节省存储空间,通常会使用简短的字符串来表示选项值,而在界面上显示更友好的完整名称。本文将介绍如何利用 Django 提供的 get_FIELD_display() 方法,在模板中轻松地显示这些完整名称。
使用 choices 属性定义选项
首先,在 models.py 文件中,使用 choices 属性定义 CharField 字段的选项。choices 属性接受一个元组列表,其中每个元组包含两个元素:
- 第一个元素是存储在数据库中的实际值(通常是简短的字符串)。
- 第二个元素是将在界面上显示的完整名称。
例如:
from django.db import models
class StuData(models.Model):
id_num = models.IntegerField(primary_key=True)
entry_date = models.DateTimeField('Date of Entry')
MALE = 'm'
FEMALE = 'f'
OTHER = 'x'
GENUNK = 'u'
GENDER_SELECTIONS = [
(MALE,'Male'),
(FEMALE,'Female'),
(OTHER,'Non-Binary'),
(GENUNK,'Unknown'),
]
gender = models.CharField(max_length=1, choices=GENDER_SELECTIONS)
## Build the selections for the race field
AFR_RACE = 'AA'
ASI_RACE = 'AS'
WHI_RACE = 'WH'
UNK_RACE = 'UN'
RACE_SELECTIONS = [
(AFR_RACE, 'African-American'),
(ASI_RACE, 'Asian/Pacific Islander'),
(WHI_RACE, 'White'),
(UNK_RACE, 'Unknown Race'),
]
race = models.CharField(max_length=2, choices=RACE_SELECTIONS)
## Build the selections for the ethnicity field
HSP = 'HIS'
NHP = 'NHP'
UNK = 'UNE'
ETHNICITY_SELECTIONS = [
(HSP, 'Hispanic Origin'),
(NHP, 'Not of Hispanic Origin'),
(UNK, 'Unknown Ethnicity'),
]
ethnicity = models.CharField(max_length=10, choices=ETHNICITY_SELECTIONS)
stu_count = models.IntegerField(default=1)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ["id_num"]
def __str__(self):
return str(self.id_num) # 修改为返回id_num字符串注意事项:
- 确保 max_length 属性足够存储最长的完整名称,或者存储数据库中实际的值。
- choices 属性是可选的,但强烈建议使用它来规范用户输入。
- __str__ 方法需要返回一个字符串,因此需要将 self.id_num 转换为字符串。
在模板中使用 get_FIELD_display() 方法
Django 提供了一个方便的方法 get_FIELD_display(),可以用来获取 choices 属性中与数据库值对应的完整名称。在模板中,可以通过以下方式使用该方法:
{% for stu in studata_list %}
{{ stu.id_num }}
{{ stu.entry_date }}
{{ stu.get_gender_display }}
{{ stu.get_race_display }}
{{ stu.get_ethnicity_display }}
{{ stu.stu_count }}
{% endfor %}在上面的代码中,stu.get_gender_display、stu.get_race_display 和 stu.get_ethnicity_display 分别会返回 gender、race 和 ethnicity 字段的完整名称,而不是存储在数据库中的简短值。
总结:
使用 get_FIELD_display() 方法可以轻松地在 Django 模板中显示 choices 属性定义的完整名称,提高用户体验。这种方法简单易用,无需编写额外的代码即可实现。记住,FIELD 应该替换为你模型中实际的字段名称。










