Choices with TextChoices
The rescue only takes in dogs, cats, and rabbits. We want to restrict an animal's species by using TextChoices, which adds a readable label to each allowed value.
Species Choices
class Animal(models.Model):
class Species(models.TextChoices):
DOG = "dog", "Dog"
CAT = "cat", "Cat"
RABBIT = "rabbit", "Rabbit"
name = models.CharField(max_length=100)
species = models.CharField(max_length=10, choices=Species)
Each choice has the value stored in the database, such as "dog", and its readable label, such as "Dog".
Species is nested inside the model, so the rest of our code refers to it as Animal.Species.DOG. Each choice is also a string, so Animal.Species.DOG is equal to the stored value "dog".
Passing Species as the field's choices limits species to those values in forms and in the admin.
Warning
choices doesn't add a database constraint. The species column accepts any string up to 10 characters long.
We also need to know each animal's adoption status, and a new animal should start out as available. We'll add the status in this chapter's exercise.