Performance: On_delete options (CASCADE, PROTECT, SET_NULL)
MEDIUM IMPACT
This affects database integrity and how related data changes impact page load and interaction speed when fetching or deleting related objects.
class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) # Deleting a Post automatically deletes related Comments in one operation.
class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.PROTECT) # Deleting a Post with many Comments raises errors and requires manual cleanup.
| Pattern | Database Queries | Deletion Blocking | Data Integrity | Verdict |
|---|---|---|---|---|
| CASCADE | Single query deletes related objects | No blocking | Automatic cleanup | [OK] Good |
| PROTECT | Multiple queries to check constraints | Blocks deletion | Prevents accidental loss | [! ] OK |
| SET_NULL | Single query sets foreign key to null | No blocking | Preserves dependent data | [OK] Good |