๐Ÿ“ Django

Django Model Relationships

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

Covered topics: ForeignKey (One-to-Many), on_delete Options, ManyToManyField (Many-to-Many), OneToOneField (One-to-One).

ForeignKey (One-to-Many)

class Project(models.Model):
    name = models.CharField(max_length=200)

class Task(models.Model):
    project = models.ForeignKey(
        Project,
        on_delete=models.CASCADE,    # delete tasks when project is deleted
        related_name='tasks',         # project.tasks.all()
        null=True, blank=True,
    )
    title = models.CharField(max_length=200)
project = Project.objects.get(pk=1)
tasks = project.tasks.all()           # reverse relation

task = Task.objects.get(pk=1)
print(task.project.name)              # forward relation

on_delete Options

Option Behavior
CASCADE Delete related objects
SET_NULL Set to NULL (requires null=True)
SET_DEFAULT Set to the field’s default value
PROTECT Prevent deletion (raises an exception)
DO_NOTHING Do nothing

ManyToManyField (Many-to-Many)

class Tag(models.Model):
    name = models.CharField(max_length=50)

class Task(models.Model):
    title = models.CharField(max_length=200)
    tags = models.ManyToManyField(Tag, blank=True, related_name='tasks')
task = Task.objects.get(pk=1)
task.tags.add(tag)             # add a tag
task.tags.remove(tag)          # remove a tag
task.tags.set([tag1, tag2])    # replace all tags
task.tags.all()                # all tags for the task

tag.tasks.all()                # all tasks with the tag

OneToOneField (One-to-One)

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    bio = models.TextField(blank=True)
    avatar = models.ImageField(upload_to='avatars/', blank=True)
user = User.objects.get(pk=1)
print(user.profile.bio)          # direct access

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 ๐Ÿ‘๏ธ 561
๐Ÿ“

settings.py: Django Configuration

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

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum