what is it?
when creating a model in django a field can be constricted to only contain certain values, adding a choices parameter
from the django documentation:
from django.db import models
YEAR_IN_SCHOOL_CHOICES = [
("FR", "Freshman"),
("SO", "Sophomore"),
("JR", "Junior"),
("SR", "Senior"),
("GR", "Graduate"),
]
class Student(models.Model):
name = models.CharField()
year = models.Charfield(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)enumeration types
these choices are similar to the standard python enum library, but with some added django magic
TextChoices
from django.db import models
class YearInSchool(models.TextChoices):
FRESHMAN = "FR", "Freshman"
SOPHOMORE = "SO", "Sophomore"
JUNIOR = "JR", "Junior"
SENIOR = "SR", "Senior"
GRADUATE = "GR", "Graduate"
class Student(models.Model):
year_in_school = models.CharField(
max_length=2,
choices=YearInSchool.choices,
default=YearInSchool.FRESHMAN,
).labelwill display the human readable nameYearInSchool.FRESHMAN.labelwill returnFreshmanYearInSchool("FR").labelwill also returnFreshman
IntegerChoices
enumeration with integers instead of text
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
class Card(models.Model):
suit = models.IntegerField(choices=Suit)can also add labels if required
class Suit(models.IntegerChoices):
DIAMOND = 1, "Diamond Card"
SPADE = 2, "Spade Card"
HEART = 3, "Heart Card"
CLUB = 4, "Club Card"