Junior — Middle
How to implement behavior when deleting a record in a table that is linked to another via on_delete?
sobes.tech AI
Answer from AI
In Django, to specify the behavior when deleting a record associated with another through a foreign key, the on_delete parameter is used in the ForeignKey field. For example:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
The on_delete values can be:
models.CASCADE— when the parent is deleted, all related records are deleted;models.PROTECT— prevents deletion of the parent if related records exist;models.SET_NULL— sets the field to NULL upon deletion of the parent (requiresnull=True);models.SET_DEFAULT— sets the default value;models.DO_NOTHING— does nothing, which may lead to integrity errors.
Thus, on_delete determines what happens to dependent records when the related record is deleted.