📝 Django

Django Model Relationships

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

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

📝

pytest-django: Testing Django

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

📅 30.06.2026 👁️ 132
📝

Django: Template Tags

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

📅 30.06.2026 👁️ 81
📝

Django: Static Files

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

📅 30.06.2026 👁️ 73

Did you like the article?

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