← Back to Django, page 2

django-0033 · Medium mid

How do you define database indexes and constraints in Django models, and why put rules in the database?

Use Meta.indexes with models.Index for query speed, and Meta.constraints with UniqueConstraint and CheckConstraint for data rules. Database constraints protect data even when code bypasses validation, for example with update(), bulk_create() or another service writing to the same tables. Since Django 4.1, model validation also checks constraints during full_clean().

Full answer

Indexes make reads faster. Constraints keep data correct. Both belong in Meta and are created by migrations.

Indexes:

  • db_index=True on a field for a simple single-column index (ForeignKeys get one automatically).
  • models.Index(fields=["room", "-exam_date"], name="mark_room_date_idx") for multi-column indexes. Column order matters: this index helps WHERE room = ... and WHERE room = ... ORDER BY exam_date DESC, not WHERE exam_date = ... alone.
  • condition=Q(...) makes a partial index on PostgreSQL and SQLite, for example only rows where is_active=True.
  • Expression indexes, such as Index(Lower("email"), name=...), for case-insensitive lookups.

Constraints:

  • UniqueConstraint(fields=["student", "subject", "exam"], name="one_mark_per_exam"). Supports condition= (unique only for some rows) and, from Django 5.0, nulls_distinct on PostgreSQL 15+.
  • CheckConstraint(condition=Q(score__gte=0) & Q(score__lte=100), name="score_0_100"). Django 5.1 renamed the argument from check= to condition=; the old name was deprecated in 5.1 and removed in 6.0.
  • unique_together still works but UniqueConstraint is preferred.

Why the database and not only Python validation? Validation in forms and serializers can be skipped by update(), bulk_create(), raw SQL, scripts and other services. Two requests can also pass a Python uniqueness check at the same time and both insert. A database constraint is the only check that closes that race.

Since Django 4.1, full_clean() validates constraints too, so forms show a friendly error before the database raises IntegrityError.

Cost: every index slows writes and uses disk. Add indexes for queries you actually run, confirmed with EXPLAIN.

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.core.exceptions import ValidationError
from django.db import models, connection, IntegrityError, transaction
from django.db.models import Q


class Mark(models.Model):
    student = models.CharField(max_length=30)
    subject = models.CharField(max_length=20)
    exam = models.CharField(max_length=10)
    score = models.IntegerField()

    class Meta:
        app_label = "school"
        indexes = [models.Index(fields=["subject", "-score"], name="mark_subject_score_idx")]
        constraints = [
            models.UniqueConstraint(fields=["student", "subject", "exam"], name="one_mark_per_exam"),
            models.CheckConstraint(condition=Q(score__gte=0) & Q(score__lte=100), name="score_0_100"),
        ]


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

Mark.objects.create(student="zoya", subject="Maths", exam="mid", score=88)

for label, kwargs in [("duplicate", dict(student="zoya", subject="Maths", exam="mid", score=90)),
                      ("score 120", dict(student="zoya", subject="Maths", exam="final", score=120))]:
    try:
        with transaction.atomic():
            Mark.objects.bulk_create([Mark(**kwargs)])  # skips Python validation
    except IntegrityError as e:
        print(label, "-> IntegrityError:", str(e).split(":")[0])

try:
    Mark(student="zoya", subject="Maths", exam="final", score=-5).full_clean()
except ValidationError as e:
    print("full_clean:", e.messages)

with connection.cursor() as cur:
    idx = connection.introspection.get_constraints(cur, Mark._meta.db_table)
print(sorted(name for name, info in idx.items() if info["index"] and not info["primary_key"]))

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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): duplicate -> IntegrityError: UNIQUE constraint failed score 120 -> IntegrityError: CHECK constraint failed full_clean: ['Constraint “score_0_100” is violated.'] ['mark_subject_score_idx']

Key points

  • Meta.indexes for speed; Meta.constraints for correctness
  • Multi-column index order matters
  • CheckConstraint uses condition= since Django 5.1; check= is gone in 6.0
  • Database constraints close race conditions Python checks cannot
  • full_clean() validates constraints since Django 4.1

Common mistakes

  • Relying only on form validation for uniqueness, which fails under concurrent requests
  • Using check= instead of condition= (deprecated in 5.1, removed in 6.0)
  • Adding indexes on every column and slowing every write
  • Ordering multi-column index fields without thinking about the queries

Follow-ups

  • How would you enforce 'only one active enrolment per student'?
  • How do you add an index to a huge PostgreSQL table without locking writes?
  • What does EXPLAIN tell you about whether an index is used?

Tips

  • Separate the purpose: indexes for speed, constraints for correctness
  • Explain the race condition that only a database constraint solves
  • Mention the Django 5.1 check= to condition= rename