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.
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.