Choices
Part of the Models and the Admin section of Coddy's Django journey. Lesson 4 of 23.
A genre should be one of a few values, not any text. The choices option limits a field to a list, given as an enumeration class. A film site could limit who a movie is for:
class Movie(models.Model):
class Age(models.TextChoices):
ALL = "all", "All ages"
TEEN = "teen", "13 and over"
ADULT = "adult", "18 and over"
age = models.CharField(max_length=10, choices=Age, default=Age.ALL)Each member has the value stored in the database, "teen", and the label people read, "13 and over". In code you write Movie.Age.TEEN, so a typo is an error rather than a new value. The class comes before the field that uses it.
Forms and the admin show the labels in a drop-down and refuse other values; the database itself does not check. movie.get_age_display() returns a row's label.
Challenge
EasyGive Book a genre:
- Inside
Book, a choices classGenre:FICTION("fiction","Fiction"),SCIFI("scifi","Science fiction"),MYSTERY("mystery","Mystery"),HISTORY("history","History"). - A field
genre, up to 20 characters, limited to those choices, fiction unless you pick another.
In the Shell tab, try Book.Genre.SCIFI.label.
Try it yourself
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2)
is_read = models.BooleanField(default=False)
finished = models.DateField(null=True, blank=True)
summary = models.TextField(blank=True)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Models and the Admin
1Your First Model
Your First ModelField Types2Querying with the ORM
Creating RowsAll and GetFilter and LookupsCounting RowsSorting RowsUpdate and DeletePractice on your own: Django playground