Data integrity and query speed are the bedrock of any enterprise application. Relying exclusively on Python-level validation is risky; network race conditions and direct database scripts can insert corrupt data. By pairing database indexes with UniqueConstraints and CheckConstraints, Django guarantees rock-solid reliability.
Here is a production example demonstrating composite indexes, conditional uniqueness, and SQL check rules:
# store/models.py
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db.models import F, Q
class Product(models.Model):
name = models.CharField(max_length=200)
sku = models.CharField(max_length=50, unique=True)
category = models.CharField(max_length=50)
# Financial fields with Python validators
price = models.DecimalField(
max_digits=8,
decimal_places=2,
validators=[MinValueValidator(0.01)]
)
discount_price = models.DecimalField(
max_digits=8,
decimal_places=2,
null=True,
blank=True
)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
indexes = [
# High-speed composite index for product filtering
models.Index(fields=['category', '-created_at'], name='idx_prod_cat_created'),
models.Index(fields=['is_active', 'price'], name='idx_prod_active_price')
]
constraints = [
# 1. SQL CHECK constraint: discount_price must be less than price
models.CheckConstraint(
condition=Q(discount_price__lt=F('price')) | Q(discount_price__isnull=True),
name='chk_discount_less_than_regular_price'
),
# 2. Conditional uniqueness: active product names must be unique within a category
models.UniqueConstraint(
fields=['category', 'name'],
condition=Q(is_active=True),
name='uniq_active_product_per_category'
)
]
def __str__(self):
return f"{self.name} ({self.sku})"
Indexes speed up SQL SELECT, WHERE, and ORDER BY queries dramatically (turning full table scans into O(log n) B-Tree lookups). However, each index incurs a minor write penalty on INSERT and UPDATE operations. Only index columns that are frequently filtered or sorted.
Broaden your backend architecture, REST API design, and production engineering expertise:
Explore field options like unique, blank, and null parameters.
Safely apply schema constraints and index migrations to production.
Bridge database-level constraints with user-facing form validation.
Prevent SQL injection, data tampering, and validation bypasses.