liveBook · Manning

TextChoices

As explained in Django in Action

TextChoices is a Django class for defining enumeration-like model-field choices with database values and human-readable labels.

TextChoices defines readable, enumeration-like values for Django model fields. Attribute values become database values, while all-capital names become sentence-case labels. section 7.2.1

class SeekingChoice(models.TextChoices):
    MUSICIAN = "M"
    BAND = "B"

Declare the permitted values as class attributes, then pass the class's .choices tuple to a CharField. section 7.2.1

A seeking-ad choice

A RiffMates SeekingAd can store MUSICIAN = "M" or BAND = "B" in its seeking field. Setting choices=MusicianBandChoice.choices restricts the field to those values, while MusicianBandChoice.MUSICIAN makes validation code clearer than comparing raw strings. section 7.2.1

How Django in Action covers it

How deep it goes
Explains declaration, label conversion, .choices usage, and a model example, but stops short of broader enumeration behavior.
Examples
Uses MUSICIAN and BAND values in the RiffMates SeekingAd model, with "M" and "B" stored in the database.
What you can do after
Apply it via Django by defining a TextChoices class and supplying its .choices attribute to a CharField.
How it connects
Connects TextChoices to CharField choices, model validation, foreign keys, and conditional clean methods.

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.