📝 Django

ForeignKey and on_delete in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
70
🌿
Level
Medium

Охватываемые темы: 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,
)
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)

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 89
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 79

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!