0
0
Djangoframework~8 mins

On_delete options (CASCADE, PROTECT, SET_NULL) in Django - Performance & Optimization

Choose your learning style9 modes available
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.
Handling deletion of related objects in Django models
Django
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

# Deleting a Post automatically deletes related Comments in one operation.
CASCADE deletes related objects automatically, reducing queries and speeding up deletion.
📈 Performance GainSingle database operation reduces queries and improves interaction speed.
Handling deletion of related objects in Django models
Django
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.PROTECT)

# Deleting a Post with many Comments raises errors and requires manual cleanup.
Using PROTECT blocks deletion and forces extra queries or manual cleanup, slowing down user actions.
📉 Performance CostBlocks deletion causing extra queries and user wait time, increasing INP.
Performance Comparison
PatternDatabase QueriesDeletion BlockingData IntegrityVerdict
CASCADESingle query deletes related objectsNo blockingAutomatic cleanup[OK] Good
PROTECTMultiple queries to check constraintsBlocks deletionPrevents accidental loss[! ] OK
SET_NULLSingle query sets foreign key to nullNo blockingPreserves dependent data[OK] Good
Rendering Pipeline
When deleting or updating related objects, Django triggers database operations that affect server response time and client rendering speed.
Database Query
Server Processing
Client Rendering
⚠️ BottleneckDatabase Query due to multiple or blocked deletions
Core Web Vital Affected
INP
This affects database integrity and how related data changes impact page load and interaction speed when fetching or deleting related objects.
Optimization Tips
1Use CASCADE to delete related objects automatically and reduce queries.
2Avoid PROTECT if you want smooth deletions without blocking user actions.
3Use SET_NULL to keep related data without deleting it, improving data stability.
Performance Quiz - 3 Questions
Test your performance knowledge
Which on_delete option automatically deletes related objects to reduce extra queries?
ACASCADE
BPROTECT
CSET_NULL
DDO_NOTHING
DevTools: Network
How to check: Open DevTools, go to Network tab, perform deletion action, and observe number and timing of API/database calls.
What to look for: Look for multiple or delayed requests indicating blocking or extra queries affecting interaction speed.