TextChoices is preferred — it provides autocompletion and avoids magic strings.
TextChoices / IntegerChoices
from django.db import models
class Task(models.Model):
class Status(models.TextChoices):
TODO = 'todo', 'To Do'
IN_PROGRESS = 'in_progress', 'In Progress'
DONE = 'done', 'Done'
class Priority(models.IntegerChoices):
LOW = 1, 'Low'
MEDIUM = 2, 'Medium'
HIGH = 3, 'High'
status = models.CharField(
max_length=20,
choices=Status,
default=Status.TODO,
)
priority = models.IntegerField(
choices=Priority,
default=Priority.MEDIUM,
)
Using Choices
# Creating
task = Task.objects.create(status=Task.Status.TODO, priority=Task.Priority.HIGH)
# Filtering
Task.objects.filter(status=Task.Status.DONE)
# Human-readable value
task.get_status_display() # 'To Do'
task.get_priority_display() # 'High'
# Iterating over options
for value, label in Task.Status.choices:
print(value, label)
In a Template
<span>{{ task.get_status_display }}</span>
<select name="status">
{% for value, label in status_choices %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select>
Old Style (without enum)
STATUS_CHOICES = [
('todo', 'To Do'),
('done', 'Done'),
]
status = models.CharField(choices=STATUS_CHOICES, max_length=20)
TextChoices is preferred — it provides autocompletion and avoids magic strings.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!