Field Types & Relationships0%
Field Types & Relationships
Beginner12 min read•Updated: Jul 11, 2026
Field Types & Relationships
Relational database design models the complex associations between real-world entities. Django provides expressive model relationship fields to enforce referential integrity across One-to-Many, Many-to-Many, and One-to-One relationships, complete with automated reverse lookup managers and cascade deletion policies.
1. The Three Relational Field Types
Output
1. ForeignKey (One-to-Many):
Author (1) ───────────< Articles (Many)
(Each article has one author; an author writes many articles)
2. ManyToManyField (Many-to-Many):
Articles (Many) >───────< Tags (Many)
(An article has multiple tags; a tag belongs to multiple articles)
3. OneToOneField (One-to-One):
User (1) ───────────── Profile (1)
(Each user has exactly one profile; each profile belongs to one user)
2. Implementing Relationships in Code
Python
# articles/models.py
from django.db import models
from django.conf import settings
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Tag(models.Model):
title = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.title
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
# One-to-Many: Author relationship
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, # Delete articles if user is deleted
related_name="articles" # Reverse lookup: user.articles.all()
)
# One-to-Many: Optional Category
category = models.ForeignKey(
Category,
on_delete=models.SET_NULL, # Keep article if category deleted, set FK to null
null=True,
blank=True,
related_name="articles"
)
# Many-to-Many: Tags (creates bridge/junction table automatically)
tags = models.ManyToManyField(Tag, related_name="articles", blank=True)
def __str__(self):
return self.title
class ArticleAnalytics(models.Model):
# One-to-One: Detailed telemetry attached to exactly one Article
article = models.OneToOneField(
Article,
on_delete=models.CASCADE,
related_name="analytics",
primary_key=True
)
bounce_rate = models.FloatField(default=0.0)
avg_read_time_seconds = models.PositiveIntegerField(default=0)
3. Deletion Policies (on_delete)
When the referenced parent object is deleted, on_delete determines the behavior on child rows:
on_delete Policy | Behavior | Best Use Case |
|---|---|---|
models.CASCADE | Automatically deletes all child records referencing the parent. | User comments or invoice line items. |
models.PROTECT | Raises ProtectedError and blocks deletion if children exist. | Deleting a Customer who has active orders. |
models.SET_NULL | Sets the foreign key column to NULL (requires null=True). | Deleting a department or optional category. |
models.SET_DEFAULT | Sets the foreign key to its configured default value. | Reassigning tickets to a default unassigned user. |
models.DO_NOTHING | Takes no action; causes database foreign key constraint failures. | Rarely recommended. |
4. Reverse Relationships with related_name
The related_name argument defines the reverse accessor name on the parent model:
Python
# Forward lookup (from child to parent):
article = Article.objects.get(id=1)
print(article.author.username)
# Reverse lookup (from parent to children):
# Without related_name: user.article_set.all()
# With related_name="articles":
author_user = User.objects.get(username="dr_sumit")
user_articles = author_user.articles.all() # Clean and expressive!
Interactive Quiz
Practice Quiz
Question 1
What happens to child Article rows if their author User is deleted and author is configured with on_delete=models.CASCADE?
Question 2
When should on_delete=models.PROTECT be used?
Question 3
What is the primary purpose of the related_name argument on ForeignKey?
Question 4
How does Django store ManyToManyField data under the hood?
Question 5
How does a OneToOneField differ from a ForeignKey with unique=True?
Next Lesson
Migrations & ORM Queries
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Creating Models | Migrations & ORM Queries |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.