Using Enum as Model Field Choice in Django

Melvin Koh
HackerNoon.com
3 min readMar 29, 2018

--

Originally published at melvinkoh.me.

In Django official documentation, they provide 2 examples on how to use predefined options as choices of a particular field.

Examples from Django Official Documentation

The first example defines choices as a Tuple of Tuple, each option being the value of the outer tuple.

The first element in each inner tuple is the value to be set in the model, and the second element being its string representation.

# Example from Django official documentation
YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
)

In their second example, they suggest us to define choices as constant in our model class.

# Example from Django official documentation
from django.db import models
class Student(models.Model):
# Constants in Model class
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)

My Preferred Way — Using Enumeration

--

--