← Back to Chapters

Model Relationships in Django

? Model Relationships in Django

? Quick Overview

Django model relationships allow you to connect data across multiple models using relational fields. The three core relationship fields are OneToOneField, ForeignKey, and ManyToManyField.

? Key Concepts

  • One-to-one relationships
  • Many-to-one relationships
  • Many-to-many relationships

? Syntax & Theory

Django provides specialized fields to define relationships directly in model definitions. These fields manage joins, constraints, and reverse lookups automatically.

? OneToOneField

? View Code Example
# Each user has exactly one profile
from django.db import models
class Profile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
bio = models.TextField()

? ForeignKey

? View Code Example
# Multiple books can belong to one author
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)

? ManyToManyField

? View Code Example
# Students can enroll in multiple courses
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
class Course(models.Model):
name = models.CharField(max_length=100)
students = models.ManyToManyField(Student)

? Explanation

  • OneToOneField creates a strict one-to-one mapping.
  • ForeignKey enables many-to-one relationships.
  • ManyToManyField supports flexible many-to-many links.

? Use Cases

  • User profiles linked to accounts
  • Blogs with multiple posts per author
  • Students enrolling in courses

? Interactive: How ForeignKey Works in DB

Simulate creating a Book linked to an Author. Watch how the database stores the relationship using an ID.

? Table: Authors

ID Name
1 J.K. Rowling
2 George R.R. Martin
3 J.R.R. Tolkien

? Table: Books (w/ ForeignKey)

ID Title author_id
No books yet...

✅ Tips & Best Practices

  • Always define on_delete behavior
  • Choose the simplest relationship that fits your data
  • Use related names for clarity

? Try It Yourself

  • Create models with each relationship type
  • Test reverse queries in Django shell
  • Explore Django Admin relationship handling