These options tell Django what to do with related data when you delete an item. It helps keep your database clean and consistent.
On_delete options (CASCADE, PROTECT, SET_NULL) in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
ForeignKey(Model, on_delete=models.CASCADE|models.PROTECT|models.SET_NULL, null=True_if_SET_NULL)
Use null=True with SET_NULL to allow empty references.
These options are used inside Django model fields to control deletion behavior.
Examples
Django
author = models.ForeignKey(User, on_delete=models.CASCADE)
Django
category = models.ForeignKey(Category, on_delete=models.PROTECT)
Django
profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)Sample Program
This example shows three models using different on_delete options to control what happens when related objects are deleted.
Django
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.PROTECT) class Profile(models.Model): user_name = models.CharField(max_length=100) class Comment(models.Model): content = models.TextField() profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) # Explanation: # Deleting an Author deletes their Books (CASCADE). # Deleting a Category is blocked if Products use it (PROTECT). # Deleting a Profile sets Comment.profile to null (SET_NULL).
Important Notes
Always choose on_delete carefully to avoid accidental data loss.
PROTECT raises an error if deletion is blocked, so handle exceptions.
SET_NULL requires null=True on the field.
Summary
CASCADE deletes related objects automatically.
PROTECT stops deletion if related objects exist.
SET_NULL sets the relation to null instead of deleting.
Practice
1. What does the
on_delete=models.CASCADE option do in Django models?easy
Solution
Step 1: Understand CASCADE behavior
The CASCADE option means when the referenced object is deleted, all related objects are also deleted automatically.Step 2: Compare with other options
Unlike PROTECT or SET_NULL, CASCADE deletes dependent objects without error or nullifying fields.Final Answer:
Deletes related objects automatically when the referenced object is deleted. -> Option AQuick Check:
CASCADE = auto-delete related objects [OK]
Hint: CASCADE means delete all linked items automatically [OK]
Common Mistakes:
- Confusing CASCADE with PROTECT which blocks deletion
- Thinking CASCADE sets fields to null instead of deleting
- Assuming CASCADE raises errors on deletion
2. Which of the following is the correct syntax to use
SET_NULL in a Django ForeignKey field?easy
Solution
Step 1: Recognize SET_NULL requires nullable field
Using SET_NULL requires the field to allow null values, sonull=Truemust be set.Step 2: Check each option for null=True
Onlymodels.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True)includesnull=Truealong with SET_NULL, making it valid syntax.Final Answer:
models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True) -> Option BQuick Check:
SET_NULL needs null=True [OK]
Hint: SET_NULL needs null=True to allow null values [OK]
Common Mistakes:
- Omitting null=True with SET_NULL causes errors
- Confusing blank=True with null=True for database nulls
- Using default=None without null=True
3. Given the models:
What happens if you try to delete an
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.PROTECT)
title = models.CharField(max_length=100)What happens if you try to delete an
Author who has related Book entries?medium
Solution
Step 1: Understand PROTECT behavior
PROTECT prevents deletion of the referenced object if related objects exist, raising an error instead.Step 2: Apply to given models
Since Book has a ForeignKey with PROTECT to Author, deleting an Author with Books will raise a ProtectedError.Final Answer:
The deletion is blocked and raises an error. -> Option DQuick Check:
PROTECT blocks deletion if related objects exist [OK]
Hint: PROTECT stops deletion if related objects exist [OK]
Common Mistakes:
- Assuming PROTECT deletes related objects like CASCADE
- Thinking PROTECT sets fields to null
- Ignoring the error raised on deletion attempt
4. Consider this model definition:
What is the error in this code?
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
content = models.TextField()What is the error in this code?
medium
Solution
Step 1: Check requirements for SET_NULL
Using SET_NULL requires the ForeignKey field to allow null values by settingnull=True.Step 2: Identify missing null=True
The code does not includenull=Trueon thepostfield, causing an error.Final Answer:
Missing null=True on the ForeignKey field. -> Option CQuick Check:
SET_NULL needs null=True [OK]
Hint: SET_NULL requires null=True on ForeignKey [OK]
Common Mistakes:
- Assuming SET_NULL works without null=True
- Confusing TextField usage with ForeignKey
- Thinking SET_NULL is invalid on ForeignKey
5. You have two models:
If a
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=100)If a
Category is deleted, what happens to the related Product entries and why is this setup useful?hard
Solution
Step 1: Understand SET_NULL with null=True
When the referenced Category is deleted, the Product's category field is set to null instead of deleting the Product.Step 2: Explain usefulness
This allows products to remain in the database without a category, which is useful if products should not be deleted just because their category is removed.Final Answer:
Products keep their category field as null; useful to retain products without category. -> Option AQuick Check:
SET_NULL + null=True keeps related objects, nullifies field [OK]
Hint: SET_NULL keeps objects, sets field null to keep data [OK]
Common Mistakes:
- Assuming related products get deleted with SET_NULL
- Thinking deletion is blocked like PROTECT
- Believing old category id remains after deletion
