Prevent deleting a User if they’re linked to existing Orders
SET_NULL
Sets the ForeignKey field to NULL
Keep Article, but set author = NULL when Author is deleted
SET_DEFAULT
Sets the ForeignKey field to its default value
If a Product is deleted, fallback to a default Category
SET(...)
Sets the ForeignKey to a custom value or callable
Set to an "archived" user when original User is deleted
DO_NOTHING
Does nothing; deletion might fail due to DB-level constraints
Advanced use with manual control; avoid unless necessary
RESTRICT(Django 3.1+)
Raises error if there are any referencing objects (like PROTECT, but stricter in behavior visibility)
Similar to PROTECT, but enforces DB constraint at the SQL level
When to Use What?
Goal
Recommended Option
Automatically delete dependents
CASCADE
Prevent deletion if used somewhere
PROTECT or RESTRICT
Allow deletion, but keep dependent object
SET_NULL or SET(...)
Replace with default
SET_DEFAULT
Full manual control
DO_NOTHING
Example Code Snippets
fromdjango.dbimportmodelsfromdjango.confimportsettingsclassPost(models.Model):author=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,null=True,blank=True,)classComment(models.Model):post=models.ForeignKey(Post,on_delete=models.CASCADE)classOrder(models.Model):user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT)classProduct(models.Model):category=models.ForeignKey("Category",on_delete=models.SET_DEFAULT,default=1# assuming category with id=1 is 'Uncategorized'
)
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)