← Back to Django, page 4

django-0061 · Easy fresher

How do you define choices on a Django field using TextChoices and IntegerChoices, and how do you display the label?

TextChoices and IntegerChoices are enumeration classes that define stored values and human labels together. Pass Class.choices to the field, compare with Class.VALUE in code, and call get_<field>_display() for the label. Django 5.0 also accepts a mapping or a callable for choices directly, and the database stores only the value.

Full answer

Hard-coded strings like "P" scattered in code are easy to mistype. Enumeration types give names:

python
class Status(models.TextChoices):
    PENDING = "P", "Pending"
    PAID = "D", "Paid"

class Fee(models.Model):
    status = models.CharField(max_length=1, choices=Status, default=Status.PENDING)
  • First tuple item is the stored value; second is the label shown in forms and admin.
  • Use Status.PAID in code (it is a str subclass, so it compares equal to "D"), Status.choices for the list of pairs, Status.values, Status.labels, and Status("D").label.
  • fee.get_status_display() returns "Paid".
  • IntegerChoices does the same for integer columns.
  • Omitting the label makes Django build one from the member name (PAID becomes "Paid").
  • Django 5.0 lets you pass the enum class itself (choices=Status) or a dict or callable; earlier versions need Status.choices.

Behaviour to remember:

  • choices restricts forms and full_clean(), but not the database or save(). A CheckConstraint with status__in=Status.values makes the database enforce it.
  • Adding or reordering choices produces a migration (choices are part of the field state), but it changes no SQL.
  • Filtering uses the stored value: Fee.objects.filter(status=Status.PAID).
  • Store stable values; labels can change or be translated with gettext_lazy.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.utils.translation import gettext_lazy as _


class Status(models.TextChoices):
    PENDING = "P", _("Pending")
    PAID = "D", _("Paid")


class Grade(models.IntegerChoices):
    FAIL = 0, "Fail"
    PASS = 1, "Pass"


class Fee(models.Model):
    status = models.CharField(max_length=1, choices=Status, default=Status.PENDING)
    result = models.IntegerField(choices=Grade.choices, default=Grade.PASS)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Fee)

fee = Fee.objects.create()
print(fee.status, fee.get_status_display(), fee.status == Status.PENDING)
fee.status = Status.PAID
fee.save()
print(Fee.objects.filter(status=Status.PAID).count(), Status.choices, Status.values)
print(Status("D").label, Status.PAID.name, Grade.FAIL.value)
print(Fee._meta.get_field("status").choices)

fee.status = "X"
fee.save()                                                    # the database accepts it
try:
    fee.full_clean()
except Exception as exc:
    print("validation:", exc.message_dict)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Passing the enum class straight to choices needs Django 5.0 or later; use Status.choices on older versions. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): P Pending True 1 [('P', 'Pending'), ('D', 'Paid')] ['P', 'D'] Paid PAID 0 [('P', 'Pending'), ('D', 'Paid')] validation: {'status': ["Value 'X' is not a valid choice."]}

Key points

  • Enumeration classes give names to stored values
  • Class.choices feeds the field; Django 5.0 also accepts the class
  • get_FOO_display() returns the label
  • choices are not enforced by the database without a CheckConstraint
  • Keep stored values stable; translate labels only

Common mistakes

  • Comparing against literal strings instead of enum members
  • Assuming choices are enforced by the database
  • Using display labels in filters or APIs
  • Changing stored values when only the label should change

Follow-ups

  • How do you translate labels?
  • How would you add a database check for the allowed values?
  • What changed in Django 5.0 for choices?

Tips

  • Describe value vs label
  • Show get_FOO_display
  • Say that save() does not validate choices