Охватываемые темы: on_delete — behavior when the parent is deleted, on_delete options, Examples, related_name.
on_delete — behavior when the parent is deleted
from django.db import models
class Task(models.Model):
project = models.ForeignKey(
'Project',
on_delete=models.CASCADE, # delete the task when the project is deleted
)
on_delete options
| Option | Behavior |
|---|---|
CASCADE |
Delete related objects |
PROTECT |
Prevent deletion if related objects exist |
SET_NULL |
Set NULL (requires null=True) |
SET_DEFAULT |
Set the field’s default value |
SET(value) |
Set a specific value |
DO_NOTHING |
Do nothing (risks referential integrity violations) |
Examples
# Delete tasks when the project is deleted
project = models.ForeignKey(Project, on_delete=models.CASCADE)
# Prevent project deletion while tasks exist
project = models.ForeignKey(Project, on_delete=models.PROTECT)
# Task without a project
project = models.ForeignKey(
Project,
on_delete=models.SET_NULL,
null=True,
blank=True,
)
related_name
class Task(models.Model):
project = models.ForeignKey(
Project,
on_delete=models.CASCADE,
related_name='tasks', # project.tasks.all()
)
project = Project.objects.get(pk=1)
tasks = project.tasks.all() # via related_name
tasks = project.task_set.all() # default (without related_name)
Choosing a strategy
- CASCADE — when a child object makes no sense without its parent (a task without a project)
- PROTECT — when deleting the parent should be a deliberate, explicit action
- SET_NULL — when the relationship is optional (an article without an author)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!