django on_delete rules
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Explanation:
Import Django models: Import the necessary modules from Django, including the
models
module.Define the Author model: Create a model class named
Author
with a single fieldname
of typeCharField
with a maximum length of 100 characters.Define the Book model: Create a model class named
Book
with two fields -title
of typeCharField
with a maximum length of 200 characters, andauthor
of typeForeignKey
related to theAuthor
model. Theon_delete=models.CASCADE
argument specifies the behavior to adopt when the referencedAuthor
object is deleted. In this case, it will also delete all relatedBook
objects.
The on_delete
argument can take various values:
models.CASCADE: When the referenced object (
Author
in this case) is deleted, also delete the objects that have a foreign key to it (Book
objects in this case).models.PROTECT: Prevent deletion of the referenced object (
Author
) by raising aProtectedError
.models.SET_NULL: Set the foreign key to
NULL
when the referenced object is deleted. Requires the field to be nullable (null=True
).models.SET_DEFAULT: Set the foreign key to its default value when the referenced object is deleted. Requires a default value to be set.
models.SET(): Set the foreign key to the value passed to
SET()
when the referenced object is deleted.models.DO_NOTHING: Do nothing when the referenced object is deleted. You are responsible for handling the situation manually.
These options provide flexibility in defining how related objects should be handled when the referenced object is deleted.