How do I get the name from an enumerated list used in a django model?

41 Views Asked by At

For example, if:

x = 'Administrative Court (KBD Admin)'

what is the syntax to retrieve the associated name 'admin' from the model choices?

model:

class CourtChoices(models.TextChoices):  # enum
    admin = ("admin", _("Administrative Court (KBD Admin)"))
    admiralty = ("admiralty", _("Admiralty Court (King’s Bench Division) (KBD Admlty)"))
    none = ("none", _("none"))
    courtname = models.CharField(max_length=100,
                                 choices=CourtChoices.choices,
                                 default="none",
                                 unique=True)
1

There are 1 best solutions below

1
weAreStarsDust On

You can convert choices to dict and switch keys and values

key_by_value = {value: key for key, value in CourtChoices.choices}

key_by_value["Administrative Court (KBD Admin)"]  # = "admin"