如何以编程方式创建 django `models.Textchoices`?

How to create a django `models.Textchoices` programmatically?

如何以编程方式创建 django models.Textchoices

django doc 中,它表明您可以定义一个 model.TextChoices

class YearInSchool(models.TextChoices):
        FRESHMAN = 'FR', _('Freshman')
        SOPHOMORE = 'SO', _('Sophomore')
        JUNIOR = 'JR', _('Junior')
        SENIOR = 'SR', _('Senior')
        GRADUATE = 'GR', _('Graduate')

如何从键值列表中以编程方式创建相同的选择class?

mapping = {
'FRESHMAN': 'FR', 'SOPHOMORE': 'SO, 'JUNIOR': 'JR', 
'SENIOR': 'SR', 'GRADUATE': 'GR'
}

# ???
YearInSchool = build_model_text_choices(mapping)

尝试将其转换为字典

mapping = {value: key for key, value in YearInSchool.choices}
actual_status = mapping[display_status]

docs生成这样的动态选择:

YearInSchool = models.TextChoices('YearInSchool', mapping)

然后你可以调用这样的选项:

YearInSchool.choices