Middle
What is IntegerChoices used for in Django?
sobes.tech AI
Answer from AI
IntegerChoices in Django is used to define a set of named integer constants. It provides a convenient and readable way to represent a fixed set of numeric values, such as statuses or types, that can be associated with model fields.
Main advantages of using IntegerChoices:
- Code readability: Constant names make the code's intent clearer than using "magic" numbers.
- Enhanced support in forms and admin interface: Django automatically generates select widgets with user-friendly labels based on constant names.
- Error prevention: Using constants instead of direct numeric values reduces the likelihood of typos.
- Centralized management: All possible values are collected in one place.
Example usage:
# choices.py or models.py
from django.db import models
class OrderStatus(models.IntegerChoices):
PENDING = 0, 'Pending'
PROCESSING = 1, 'Processing'
SHIPPED = 2, 'Shipped'
DELIVERED = 3, 'Delivered'
CANCELLED = 4, 'Cancelled'
# models.py
from django.db import models
from .choices import OrderStatus # If OrderStatus is defined in another file
class Order(models.Model):
status = models.IntegerField(
choices=OrderStatus.choices,
default=OrderStatus.PENDING,
)
created_at = models.DateTimeField(auto_now_add=True)
# In code
order = Order.objects.create(status=OrderStatus.PROCESSING)
if order.status == OrderStatus.DELIVERED:
print("Order delivered")