Foreign Keys On_Delete Option in Django Models
Last Updated :
25 Apr, 2025
In Django models, the on_delete
option is used to specify the behavior that should be taken when the referenced object (usually a foreign key target) is deleted. This option is crucial for maintaining data integrity and handling relationships between models. The on_delete
option is required when you define a ForeignKey
field in a model.
What is the On_Delete Option in Django Models?
In Django models, the on_delete
option is used to specify the behavior to adopt when the referenced object (foreign key) is deleted. This option is typically used in ForeignKey fields, which establish a relationship between two models.
Foreign Keys On_Delete Option in Django Models
Below, are the Foreign Keys used in On_Delete Option In Django Models in Python:
- CASCADE
- PROTECT
- RESTRICT
- SET_NULL
- SET_DEFAULT
- SET()
- DO_NOTHING
CASCADE
This option means that when the referenced object is deleted in objects then all the objects that have a foreign key to it will also be deleted. This method helps us in ensuring that child objects are cleaned up when all the parent object are deleted.
models.py
Python
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)
PROTECT
This option prevents deletion of the referenced object. If there are related objects (with foreign keys pointing to it), an error will be raised preventing the deletion of the referenced object.To delete it you will have to delete all objects that reference it manually.
models.py
Python
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.PROTECT)
RESTRICT
Similar to 'PROTECT'
, but raises a more specific ProtectedError
exception, which can be helpful for distinguishing between different types of protection errors.
models.py
Python
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.RESTRICT)
SET_NULL
When the referenced object is deleted, the foreign key in related objects will be set to NULL
(if the field allows null values). This is often used when you want to preserve the relationships but remove the direct connection to the deleted object.
models.py
Python
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.SET_NULL)
SET_DEFAULT
Similar to 'SET_NULL'
, but the foreign key will be set to its default value instead of NULL
.
models.py
Python
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, default="Default", on_delete=models.SET_DEFAULT)
SET()
This option allows you to specify a callable (usually a function) that will be called to set the value of the foreign key when the referenced object is deleted.
models.py
Python
def custom_author():
return Author.objects.get(name='Unknown')
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.SET(custom_author))
DO_NOTHING
This option doesn't perform any action when the referenced object is deleted. It leaves the responsibility of handling the relationship to you.
models.py
Python
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.DO_NOTHING)
Understanding the on_delete option is critical for managing database relationships in Django. To master Django models and other advanced features, the Django Web Development Course - Basics to Advance offers extensive learning opportunities.
Similar Reads
How to Make the Foreign Key Field Optional in Django Model?
When working with the relational database, we often need to add foreign key relationships between tables. However, when working with Django, we can simply add models.ForeignKey field to a model to relate it with some other model. By default, this field will be a required field, which means we can't
4 min read
Built-in Field Validations - Django Models
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a p
3 min read
Python | Relational fields in Django models
Prerequisite: Django models Django models represent real-world entities, and it is rarely the case that real-world entities are entirely independent of each other. Hence Django supports relational databases and allows us to establish relations between different models. There are three types of relat
4 min read
How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models
2 min read
Delete Multiple Objects at Once in Django
In Django, deletions of objects are very common once we want to delete outdated information or information we no longer have a need for within our database. Django ORM provides several and efficient ways to delete models instances. To delete instances in Django, we can use either of the following me
3 min read
How to Efficiently Delete a Record in Django
In Django, deleting a record (or row) from a database table associated with a model is straightforward. Django models provide a delete() method that can be called on an individual object, or on a QuerySet of objects to remove them from the database. Deleting records is a fundamental operation, often
9 min read
Setting Default Value for Foreign Key Attribute in Django
In Django, ForeignKey is a field used to define a one-to-many relationship between two models. It creates a relationship where a field in one model references a row in another model. This is commonly used in scenarios like blog posts having an author or an order being associated with a customer. For
4 min read
CRUD Operation On A Django Model With A Many-to-Many Field
Django provides a powerful and flexible way to work with relational databases through its Object-Relational Mapping (ORM). One of the common relationships we encounter in database design is the Many-to-Many relationship. In Django, this relationship is represented using a ManyToManyField. In this ar
4 min read
Custom Field Validations in Django Models
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself
3 min read
How to Filter ForeignKey Choices in a Django ModelForm
A ForeignKey field allows one model to relate to another in Django. When this field is represented in a form (e.g., a Django ModelForm), it typically displays a dropdown list (a select box) populated with all the objects from the related model. However, there are many scenarios where we may need to
7 min read