Django model relationships allow you to connect data across multiple models using relational fields. The three core relationship fields are OneToOneField, ForeignKey, and ManyToManyField.
Django provides specialized fields to define relationships directly in model definitions. These fields manage joins, constraints, and reverse lookups automatically.
# 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()
# 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)
# 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)
Simulate creating a Book linked to an Author. Watch how the database stores the relationship using an ID.
| ID | Name |
|---|---|
| 1 | J.K. Rowling |
| 2 | George R.R. Martin |
| 3 | J.R.R. Tolkien |
| ID | Title | author_id |
|---|---|---|
| No books yet... | ||
on_delete behavior