← Back to Django, page 1

django-0011 · Easy fresher

What does on_delete do on a Django ForeignKey, and when would you use CASCADE, PROTECT, SET_NULL or RESTRICT?

on_delete tells Django what to do with child rows when the parent row they point to is deleted. CASCADE deletes the children too, PROTECT blocks the delete by raising ProtectedError, SET_NULL sets the foreign key to NULL (needs null=True), SET_DEFAULT uses the field default, and RESTRICT blocks unless the children are being deleted through another cascade.

Full answer

A ForeignKey creates a many-to-one link: many Marks rows can point to one Student. on_delete is required and decides what happens to those Marks when the Student is deleted.

Options:

  • CASCADE: delete the children as well. Good when a child has no meaning without the parent, such as order lines without an order.
  • PROTECT: refuse to delete the parent while children exist, raising ProtectedError. Good for reference data, such as a Course that still has enrolled students.
  • SET_NULL: keep the child and set the link to NULL. The field needs null=True. Good for "the teacher left but keep the class record".
  • SET_DEFAULT / SET(value_or_callable): point to a default or a computed value.
  • RESTRICT (Django 3.1+): like PROTECT, but allows the delete if the child is also being removed through a CASCADE from another path.
  • DO_NOTHING: Django does nothing; the database decides, which usually means an integrity error.

Django emulates these rules in Python, not with database ON DELETE clauses. It collects related objects, fires pre_delete/post_delete signals, and deletes in the right order. That has two effects: deleting one parent with many children can run many queries, and raw SQL deletes that bypass the ORM do not cascade. Django 6.1 (August 2026) adds database-level options, DB_CASCADE, DB_SET_NULL and DB_SET_DEFAULT, which use the SQL ON DELETE clause and skip loading the child objects; DB_CASCADE does not send delete signals.

related_name sets the reverse accessor: student.marks.all() instead of student.marks_set.all().

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.db import models, connection
from django.db.models import ProtectedError


class Course(models.Model):
    name = models.CharField(max_length=40)
    class Meta:
        app_label = "school"


class Teacher(models.Model):
    name = models.CharField(max_length=40)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    course = models.ForeignKey(Course, on_delete=models.PROTECT, related_name="students")
    mentor = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, related_name="mentees")
    class Meta:
        app_label = "school"


class Marks(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (Course, Teacher, Student, Marks):
        editor.create_model(m)

bca = Course.objects.create(name="BCA")
mentor = Teacher.objects.create(name="Mr. Iyer")
s = Student.objects.create(name="Farah", course=bca, mentor=mentor)
Marks.objects.create(student=s, score=72)

mentor.delete()
s.refresh_from_db()
print("mentor after SET_NULL:", s.mentor)

try:
    bca.delete()
except ProtectedError:
    print("PROTECT stopped deleting a course that has students")

print(s.delete())  # CASCADE removes the marks too

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): mentor after SET_NULL: None PROTECT stopped deleting a course that has students (2, {'school.Marks': 1, 'school.Student': 1})

Key points

  • on_delete runs when the parent row is deleted
  • CASCADE removes children; PROTECT and RESTRICT block deletes
  • SET_NULL needs null=True
  • Django emulates on_delete in Python, not in the database
  • related_name names the reverse accessor

Common mistakes

  • Using CASCADE on reference data and wiping out history by deleting one row
  • Using SET_NULL without null=True, which fails at system check time
  • Assuming raw SQL deletes follow on_delete rules
  • Not setting related_name and getting confusing _set accessors or clashes

Follow-ups

  • Why might deleting one user with CASCADE be slow?
  • What is the difference between PROTECT and RESTRICT?
  • How would you implement soft delete instead of a real delete?

Tips

  • Pair each option with a real-world example
  • Mention that Django emulates cascades in Python
  • Bring up soft delete for records that must be kept for audit