Python - Covert enum to Django models.CharField choices tuple

Viewed 1145

I have this enum:

class Animal(Enum):
  DOG = 'dog'
  CAT = 'cat'

and in a Django model I have this:

possible_animals = (
  ("DOG", "dog"),
  ("cat", "cat"),
)
animal = models.CharField(choices=possible_animals, ...)

I know I can use the enum like this:

possible_animals = (
  (Animal.DOG.name, Animal.DOG.value),
  (Animal.CAT.name, Animal.CAT.value),
)

but is there any other elegant dynamic way to convert the enum into this kind of nested tuple?

1 Answers

Create enum class by inheriting the models.TextChoices as

class AnimalModel(models.Model):
    class Animal(models.TextChoices):
        DOG = 'dog'
        CAT = 'cat'

    animal = models.CharField(choices=Animal.choices)
Related