Summary: In this tutorial, you will learn the significance of the on_delete parameter in ForeignKey field in Django.

In Django, the on_delete parameter is used to specify what should happen to objects that have a foreign key relationship with the object being deleted.

For example, consider the following models:

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

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

In this example, the Book model has a foreign key relationship with the Author model, which means that each Book instance is related to a specific Author instance.

The on_delete parameter specifies what should happen to the Book instances if the related Author instance is deleted.

There are several options for the on_delete parameter:

  • models.CASCADE: This will delete all the related Book instances when the Author instance is deleted.
  • models.PROTECT: This will prevent the related Author instance from being deleted if there are any related Book instances.
  • models.SET_NULL: This will set the author field of the related Book instances to NULL when the Author instance is deleted.
  • models.SET_DEFAULT: This will set the author field of the related Book instances to the default value specified in the field definition when the Author instance is deleted.
  • models.SET(): This will set the author field of the related Book instances to a specified value when the Author instance is deleted.

For example, if you set on_delete=models.CASCADE, then if you delete an Author instance, all the related Book instances will also be deleted.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply