DEV Community

DoriDoro
DoriDoro

Posted on

Cheat Sheet for all Django `on_delete` options

Django on_delete Cheat Sheet

Option What Happens When Referenced Object is Deleted? Use Case Example
CASCADE Also delete the object with the ForeignKey Delete all Comments when a Post is deleted
PROTECT Raises ProtectedError and prevents deletion 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

from django.db import models
from django.conf import settings

class Post(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)

class Product(models.Model):
    category = models.ForeignKey(
        "Category",
        on_delete=models.SET_DEFAULT,
        default=1  # assuming category with id=1 is 'Uncategorized'
    )
Enter fullscreen mode Exit fullscreen mode

Top comments (0)