Django on_delete – Advanced Django Concepts
The on_delete
attribute is a parameter used in Django to specify what should happen when an item that is referenced by a ForeignKey is deleted.
Syntax
models.ForeignKey(to, on_delete)
Example
Let's consider a simple example of models.py with a foreign key relationship. Here is the code snippet:
class Country(models.Model):
name = models.CharField(max_length=50, unique=True)
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
Here, City
model has a foreign key relationship with Country
using on_delete
parameter.
Explanation
The on_delete
attribute is mandatory for ForeignKey
field. It specifies how to handle when a referenced object is deleted.
Here are the following possible values for on_delete
:
models.CASCADE
: This value deletes the object containing the foreign key when the referenced object is deleted.models.PROTECT
: This value prevents deletion of the referenced object when related objects still have references to it.models.SET_NULL
: This value sets the foreign key toNULL
when the referenced object is deleted. This requires the foreign key to havenull=True
.models.SET_DEFAULT
: This value sets the foreign key to its default value when the referenced object is deleted.models.DO_NOTHING
: This value does nothing.
Use
on_delete
attribute is used in ForeignKey fields to specify the behavior that should occur when the referenced object is deleted.
Important Points
on_delete
attribute is mandatory for the ForeignKey field.- Different values can be used for
on_delete
attribute. - Use
CASCADE
with caution, as it may cause unexpected delete on related objects. - It is a good practice to use
on_delete=models.PROTECT
for critical data relationships.
Summary
on_delete
attribute is an important identifier used in Django to specify the behavior that should occur when the referenced object is deleted. It is a mandatory attribute for the ForeignKey
field in Django. Various values of on_delete
provide different behaviors to handle data referencing in Django. Always use appropriate on_delete
behavior depending upon the project requirement.