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:

  1. Import Django models: Import the necessary modules from Django, including the models module.

  2. Define the Author model: Create a model class named Author with a single field name of type CharField with a maximum length of 100 characters.

  3. Define the Book model: Create a model class named Book with two fields - title of type CharField with a maximum length of 200 characters, and author of type ForeignKey related to the Author model. The on_delete=models.CASCADE argument specifies the behavior to adopt when the referenced Author object is deleted. In this case, it will also delete all related Book 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 a ProtectedError.

  • 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.