๐Ÿ“ Django

ForeignKey and on_delete in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
310
๐ŸŒฟ
Level
Medium

Covered topics: 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

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 279
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 563
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315

Did you like the article?

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