Skip to content

Instantly share code, notes, and snippets.

@JackAtOmenApps
Last active November 28, 2023 15:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JackAtOmenApps/3eef60ba4204f3d1842d9d7477efcce1 to your computer and use it in GitHub Desktop.
Save JackAtOmenApps/3eef60ba4204f3d1842d9d7477efcce1 to your computer and use it in GitHub Desktop.
Example of the new django 3.0 TextChoices enumeration types
from django.db import models
class Animal(models.Model):
class AnimalType(models.TextChoices):
ANTELOPE = 'A', 'Antelope'
BAT = 'B', 'Bat'
COUGAR = 'C', 'Cougar'
animal_type = models.CharField(max_length=1, choices=AnimalType.choices, default=AnimalType.ANTELOPE)
# In this example, the middle value on each line is what is saved to the database. So, `B` if I selected Bat. Since I am only using one character for each possible entry in this example, I set the `max_length` to 1.
>>> # Working with the AnimalType class itself outside of the Animal model
>>>
>>> Animal.AnimalType.values
['A', 'B', 'C']
>>>
>>> Animal.AnimalType.names
['ANTELOPE', 'BAT', 'COUGAR']
>>>
>>> Animal.AnimalType.labels
['Antelope', 'Bat', 'Cougar']
>>>
>>> Animal.AnimalType.choices
[('A', 'Antelope'), ('B', 'Bat'), ('C', 'Cougar')]
>>>
>>> dict(Animal.AnimalType.choices)
{'A': 'Antelope', 'B': 'Bat', 'C': 'Cougar'}
>>>
>>> # Working with AnimalType in a Model Instance
>>> my_animal = Animal()
>>> my_animal.save()
>>>
>>> my_animal_type = my_animal.animal_type
>>>
>>> # To get the value saved to the database:
>>> str(my_animal.animal_type)
'A'
>>>
>>> # To get the display name:
>>> # https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.get_FOO_display
>>> my_animal.get_animal_type_display()
'Antelope'
@JackAtOmenApps
Copy link
Author

@AmoahDevLabs
Copy link

Nice one. Very simple and straight forward.

@ayee
Copy link

ayee commented Mar 17, 2023

Do you know how labels are stored in database?

@ramona-2020
Copy link

You can access labels with Animal.AnimalType.labels

@pavelsmirnov
Copy link

Hi, how can I make a Text Choices field editable in django admin? For example, I would like to allow admin to add his own values if there is no suitable value? Trying googling but can't find solution yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment