Add Choices to a Model Field
A snippet showing how to add predefined choices to Django model fields.
# models.py
from django.db import models
class Task(models.Model):
STATUS_CHOICES = [
('PENDING', 'Pending'),
('IN_PROGRESS', 'In Progress'),
('COMPLETED', 'Completed'),
]
title = models.CharField(max_length=100)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING')
def __str__(self):
return f"{self.title} ({self.get_status_display()})"
# Django Shell
# python manage.py shell
>>> from tasks.models import Task
>>> task = Task.objects.create(title='Write Article', status='IN_PROGRESS')
>>> task.status
'IN_PROGRESS'
>>> task.get_status_display()
'In Progress'
# Alternative with Enums (Recommended)
from django.db import models
class Status(models.TextChoices):
PENDING = 'PENDING', 'Pending'
IN_PROGRESS = 'IN_PROGRESS', 'In Progress'
COMPLETED = 'COMPLETED', 'Completed'
class Task(models.Model):
title = models.CharField(max_length=100)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
def __str__(self):
return f"{self.title} ({self.get_status_display()})"
Explanation:
-
The
choicesoption restricts a field's value to a predefined list of valid options. -
Each choice is a tuple of
(value, label). The value is stored in the DB, and the label is displayed in forms/admin. -
get_FOO_display()lets you access the human-readable version of the field value. -
Using
TextChoicesis cleaner and reusable, making your model easier to maintain.
- Category Models & ORM
- Total Views 1296
- Last Modified 15 September, 2025
- Tags #models #fields #choices #orm
Previous snippet
Define a Simple Django Model
Next snippet