Home > database >  How to create a django `models.Textchoices` programmatically?
How to create a django `models.Textchoices` programmatically?

Time:02-05

How to create a django models.Textchoices programmatically?

In the django doc, it shows you can define a model.TextChoices with:

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

How can I create programmatically the same choices class from a list of key, values?

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

# ???
YearInSchool = build_model_text_choices(mapping)

CodePudding user response:

Try to convert it to a dict

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

CodePudding user response:

Try this:

def build_model_text_choices(mapping, class_name):
   for key, value in mapping.items():
      setattr(class_name, key, value)
  •  Tags:  
  • Related