Concept Flow - On_delete options (CASCADE, PROTECT, SET_NULL)
Delete Parent Object
Check on_delete option
CASCADE
End
When a parent object is deleted, Django checks the on_delete option to decide what happens to related child objects.
Jump into concepts and practice - no test required
class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) # Deleting an Author triggers on_delete behavior on Book
| Step | Action | on_delete Option | Effect on Child Object | Result |
|---|---|---|---|---|
| 1 | Delete Author object | CASCADE | Delete all related Book objects | Books deleted automatically |
| 2 | Delete Author object | PROTECT | Prevent deletion if related Book exists | Error raised, Author not deleted |
| 3 | Delete Author object | SET_NULL | Set Book.author to NULL if allowed | Author deleted, Books remain with author=NULL |
| 4 | Delete Author object | Other (e.g. DO_NOTHING) | No automatic action on Book | Possible DB error if FK constraint violated |
| 5 | End | - | - | Process complete |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| Author Exists | True | False (CASCADE) | True (PROTECT) | False (SET_NULL) | Depends on option |
| Book Count | 5 | 0 (CASCADE) | 5 (PROTECT) | 5 (SET_NULL, author=NULL) | Depends on option |
| Book.author FK | Author ID | N/A (deleted) | Author ID | NULL | Depends on option |
Django on_delete options control child object behavior when parent is deleted: - CASCADE: deletes child objects automatically - PROTECT: blocks deletion if children exist - SET_NULL: sets FK to NULL if allowed Choose based on desired data integrity and app logic.
on_delete=models.CASCADE option do in Django models?SET_NULL in a Django ForeignKey field?null=True must be set.models.ForeignKey(OtherModel, on_delete=models.SET_NULL, null=True) includes null=True along with SET_NULL, making it valid syntax.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)Author who has related Book entries?class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
content = models.TextField()null=True.null=True on the post field, causing an error.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)Category is deleted, what happens to the related Product entries and why is this setup useful?