0
0
Djangoframework~5 mins

On_delete options (CASCADE, PROTECT, SET_NULL) in Django

Choose your learning style9 modes available
Introduction

These options tell Django what to do with related data when you delete an item. It helps keep your database clean and consistent.

When deleting a user should also delete all their posts (CASCADE).
When you want to prevent deleting a category if products still use it (PROTECT).
When deleting a parent object but want to keep child objects with a blank reference (SET_NULL).
Syntax
Django
ForeignKey(Model, on_delete=models.CASCADE|models.PROTECT|models.SET_NULL, null=True_if_SET_NULL)

Use null=True with SET_NULL to allow empty references.

These options are used inside Django model fields to control deletion behavior.

Examples
Deletes all posts if the author is deleted.
Django
author = models.ForeignKey(User, on_delete=models.CASCADE)
Prevents deleting a category if products still belong to it.
Django
category = models.ForeignKey(Category, on_delete=models.PROTECT)
Sets profile to null if the related profile is deleted.
Django
profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
Sample Program

This example shows three models using different on_delete options to control what happens when related objects are deleted.

Django
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Category(models.Model):
    name = models.CharField(max_length=100)

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)

class Profile(models.Model):
    user_name = models.CharField(max_length=100)

class Comment(models.Model):
    content = models.TextField()
    profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)

# Explanation:
# Deleting an Author deletes their Books (CASCADE).
# Deleting a Category is blocked if Products use it (PROTECT).
# Deleting a Profile sets Comment.profile to null (SET_NULL).
OutputSuccess
Important Notes

Always choose on_delete carefully to avoid accidental data loss.

PROTECT raises an error if deletion is blocked, so handle exceptions.

SET_NULL requires null=True on the field.

Summary

CASCADE deletes related objects automatically.

PROTECT stops deletion if related objects exist.

SET_NULL sets the relation to null instead of deleting.