这就是我尝试在 models.py
中定义模型的方式
from django.db import models
class Country(models.Model):
class Countries(models.TextChoices):
US = 'US', 'United States'
EP = 'EP', 'Europe'
IND = 'IN', 'India'
name = models.CharField(max_length=2,
choices=Countries.choices,
blank=True)
def __str__(self):
return getattr(self.Countries, self.name)
str 调用只给出两个字母的国家代码。如何获取完整信息,例如 US(美国)
或 US, United States
当我在 admin
中手动添加国家/地区时,它会显示全名。它一定是以某种方式获取的。
最佳答案
使用get_FOO_display()
(Django Doc)方法
class Country(models.Model):
# other fields
def __str__(self):
return <b>"{value} ({display_value})".format(value=self.name, display_value=self.get_name_display())</b>
关于python - 如何在 __str__ 方法中获取 TextChoice 枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606682/