Bird
Raised Fist0
Djangoframework~20 mins

On_delete options (CASCADE, PROTECT, SET_NULL) in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
On_delete Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a parent object is deleted with CASCADE?
Consider a Django model where a child model has a ForeignKey to a parent model with on_delete=models.CASCADE. What is the behavior when the parent object is deleted?
Django
class Parent(models.Model):
    name = models.CharField(max_length=100)

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
AAll child objects linked to the parent are deleted automatically.
BThe deletion of the parent is blocked and raises an error.
CThe parent is deleted but child objects keep their foreign key pointing to a non-existent parent.
DThe foreign key in child objects is set to NULL, but the child objects remain.
Attempts:
2 left
💡 Hint
Think about what CASCADE means in everyday life, like a waterfall effect.
component_behavior
intermediate
2:00remaining
What error occurs with PROTECT on deleting a parent?
If a ForeignKey uses on_delete=models.PROTECT, what happens when you try to delete the parent object that has child objects linked to it?
Django
class Parent(models.Model):
    name = models.CharField(max_length=100)

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.PROTECT)
    name = models.CharField(max_length=100)
AThe parent is deleted and child objects are also deleted.
BThe parent is deleted and child foreign keys are set to NULL.
CA ProtectedError is raised and the parent deletion is blocked.
DThe parent is deleted but child foreign keys point to a missing parent.
Attempts:
2 left
💡 Hint
PROTECT means to stop something from happening.
component_behavior
advanced
2:00remaining
What is the effect of SET_NULL on deleting a parent object?
Given a ForeignKey with on_delete=models.SET_NULL and null=True, what happens to child objects when the parent is deleted?
Django
class Parent(models.Model):
    name = models.CharField(max_length=100)

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=100)
AChild objects are deleted along with the parent.
BChild objects keep their foreign key pointing to the deleted parent.
CDeletion of the parent is blocked with an error.
DChild objects remain and their foreign key is set to NULL.
Attempts:
2 left
💡 Hint
Think about removing a link but keeping the child safe.
📝 Syntax
advanced
2:00remaining
Which ForeignKey declaration is correct for SET_NULL?
You want to use on_delete=models.SET_NULL in a ForeignKey. Which option is syntactically correct and will work without errors?
Aparent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True)
Bparent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null=True)
Cparent = models.ForeignKey(Parent, on_delete=models.SET_NULL)
Dparent = models.ForeignKey(Parent, on_delete=models.SET_NULL, default=None)
Attempts:
2 left
💡 Hint
SET_NULL requires the field to accept NULL values.
state_output
expert
3:00remaining
What is the count of Child objects after deleting a Parent with mixed on_delete behaviors?
Given these models and data, what is the number of Child objects remaining after deleting the Parent with id=1?
Django
class Parent(models.Model):
    name = models.CharField(max_length=100)

class ChildCascade(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)

class ChildProtect(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.PROTECT)

class ChildSetNull(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null=True)

# Setup:
# Parent object with id=1 exists
# ChildCascade objects linked to Parent 1: 3
# ChildProtect objects linked to Parent 1: 2
# ChildSetNull objects linked to Parent 1: 4

# Action:
# Attempt to delete Parent with id=1
ADeletion fails with ProtectedError; all 9 child objects remain
B4 child objects remain: only SetNull children with foreign keys set to NULL
C5 child objects remain: 2 Protect and 3 SetNull (SetNull children foreign keys set to NULL)
D9 child objects remain: 3 Cascade, 2 Protect, 4 SetNull
Attempts:
2 left
💡 Hint
PROTECT blocks deletion if any child exists.

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

  1. Step 1: Understand CASCADE behavior

    The CASCADE option means when the referenced object is deleted, all related objects are also deleted automatically.
  2. Step 2: Compare with other options

    Unlike PROTECT or SET_NULL, CASCADE deletes dependent objects without error or nullifying fields.
  3. Final Answer:

    Deletes related objects automatically when the referenced object is deleted. -> Option A
  4. 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

  1. Step 1: Recognize SET_NULL requires nullable field

    Using SET_NULL requires the field to allow null values, so null=True must be set.
  2. 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.
  3. Final Answer:

    models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True) -> Option B
  4. 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

  1. Step 1: Understand PROTECT behavior

    PROTECT prevents deletion of the referenced object if related objects exist, raising an error instead.
  2. Step 2: Apply to given models

    Since Book has a ForeignKey with PROTECT to Author, deleting an Author with Books will raise a ProtectedError.
  3. Final Answer:

    The deletion is blocked and raises an error. -> Option D
  4. 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

  1. Step 1: Check requirements for SET_NULL

    Using SET_NULL requires the ForeignKey field to allow null values by setting null=True.
  2. Step 2: Identify missing null=True

    The code does not include null=True on the post field, causing an error.
  3. Final Answer:

    Missing null=True on the ForeignKey field. -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Products keep their category field as null; useful to retain products without category. -> Option A
  4. 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
  • Thinking deletion is blocked like PROTECT
  • Believing old category id remains after deletion