Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using on_delete Options in Django Models
📖 Scenario: You are building a simple Django app to manage books and their authors. Each book is linked to one author.When an author is deleted, you want to control what happens to their books using different on_delete options.
🎯 Goal: Create Django models for Author and Book with a foreign key from Book to Author. Use the on_delete options CASCADE, PROTECT, and SET_NULL in different steps to see how they affect deleting authors.
📋 What You'll Learn
Create an Author model with a name field
Create a Book model with a title field and a foreign key to Author
Use on_delete=models.CASCADE in Step 3
Use on_delete=models.PROTECT in Step 3
Use on_delete=models.SET_NULL with null=True in Step 3
💡 Why This Matters
🌍 Real World
Managing related data in web apps is common. Knowing how to handle deletions safely prevents data loss or errors.
💼 Career
Django developers often design database models and must choose appropriate on_delete behaviors to maintain data integrity.
Progress0 / 4 steps
1
Create the Author model
Create a Django model called Author with a single field name that is a CharField with max length 100.
Django
Hint
Use models.CharField(max_length=100) for the name field inside the Author model class.
2
Create the Book model with a foreign key to Author
Create a Django model called Book with a title field as a CharField with max length 200, and a foreign key field called author that links to the Author model. Do not add on_delete yet.
Django
Hint
Use models.ForeignKey(Author, on_delete=models.CASCADE) for the author field. We will change on_delete in the next step.
3
Change on_delete to CASCADE, PROTECT, and SET_NULL
Modify the author foreign key in the Book model to use on_delete=models.CASCADE. Then, create two more versions of the Book model called BookProtect and BookSetNull where the author foreign key uses on_delete=models.PROTECT and on_delete=models.SET_NULL respectively. For BookSetNull, add null=True to the foreign key field.
Django
Hint
Use on_delete=models.CASCADE for Book, on_delete=models.PROTECT for BookProtect, and on_delete=models.SET_NULL, null=True for BookSetNull.
4
Add __str__ methods for better display
Add a __str__ method to each model (Author, Book, BookProtect, and BookSetNull) that returns the name for Author and the title for the book models.
Django
Hint
Define __str__ methods that return self.name for Author and self.title for the book models.
Practice
(1/5)
1. What does the on_delete=models.CASCADE option do in Django models?
easy
A. Deletes related objects automatically when the referenced object is deleted.
B. Prevents deletion of the referenced object if related objects exist.
C. Sets the related field to null instead of deleting the object.
D. Raises an error if the related object is missing.
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 A
Quick 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
A. models.ForeignKey(OtherModel, on_delete=models.SET_NULL)
B. models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True)
C. models.ForeignKey(OtherModel, on_delete=models.SET_NULL, blank=True)
D. models.ForeignKey(OtherModel, on_delete=models.SET_NULL, default=None)
Solution
Step 1: Recognize SET_NULL requires nullable field
Using SET_NULL requires the field to allow null values, so null=True must be set.
Step 2: Check each option for null=True
Only models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True) includes null=True along with SET_NULL, making it valid syntax.
Final Answer:
models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True) -> Option B
Quick 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:
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
A. The author is deleted but books remain with invalid author references.
B. The author is deleted and all related books are deleted too.
C. The author is deleted and the book's author field is set to null.
D. The deletion is blocked and raises an error.
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 D
Quick 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:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
content = models.TextField()
What is the error in this code?
medium
A. No error, the code is correct.
B. ForeignKey cannot use SET_NULL as on_delete option.
C. Missing null=True on the ForeignKey field.
D. TextField cannot be used with ForeignKey.
Solution
Step 1: Check requirements for SET_NULL
Using SET_NULL requires the ForeignKey field to allow null values by setting null=True.
Step 2: Identify missing null=True
The code does not include null=True on the post field, causing an error.
Final Answer:
Missing null=True on the ForeignKey field. -> Option C
Quick 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:
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
A. Products keep their category field as null; useful to retain products without category.
B. Products are deleted automatically; useful to keep database clean.
C. Deletion is blocked; useful to prevent accidental data loss.
D. Products keep old category id; useful for historical reference.
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 A
Quick 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