Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Covert enum to Django models.CharField choices tuple [duplicate]

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?

like image 767
ET-CS Avatar asked Jan 26 '26 11:01

ET-CS


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)
like image 166
JPG Avatar answered Jan 29 '26 00:01

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!