What if deleting one item could silently break your whole database without warning?
Why On_delete options (CASCADE, PROTECT, SET_NULL) in Django? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a list of books linked to authors in a database. When you delete an author manually, you must remember to update or remove all their books too, or your data will be messy and broken.
Manually handling related data deletions is slow and risky. You might forget to delete or update linked records, causing errors or inconsistent data that confuse users and crash your app.
Django's on_delete options like CASCADE, PROTECT, and SET_NULL automatically manage related data when you delete an object, keeping your database clean and consistent without extra work.
if author_deleted: for book in books: if book.author == author: delete_or_update(book)
author = Author.objects.get(id=1) author.delete() # related books handled automatically by on_delete
This lets you safely delete or protect related data with simple rules, so your app stays reliable and your code stays clean.
When an author is removed from a library system, all their books can be deleted automatically (CASCADE), or deletion can be blocked if books exist (PROTECT), or books can keep their record but lose the author link (SET_NULL).
Manual deletion of related data is error-prone and tedious.
on_delete options automate data consistency when deleting linked records.
CASCADE, PROTECT, and SET_NULL cover common real-world needs safely and simply.
Practice
on_delete=models.CASCADE option do in Django models?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]
- Confusing CASCADE with PROTECT which blocks deletion
- Thinking CASCADE sets fields to null instead of deleting
- Assuming CASCADE raises errors on deletion
SET_NULL in a Django ForeignKey field?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]
- Omitting null=True with SET_NULL causes errors
- Confusing blank=True with null=True for database nulls
- Using default=None without null=True
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?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]
- Assuming PROTECT deletes related objects like CASCADE
- Thinking PROTECT sets fields to null
- Ignoring the error raised on deletion attempt
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
content = models.TextField()What is the error in this code?
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]
- Assuming SET_NULL works without null=True
- Confusing TextField usage with ForeignKey
- Thinking SET_NULL is invalid on ForeignKey
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?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]
- Assuming related products get deleted with SET_NULL
- Thinking deletion is blocked like PROTECT
- Believing old category id remains after deletion
