MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Field Types & Relationships0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
2.1Creating Models2.2Field Types & Relationships2.3Migrations & ORM Queries
HomeTutorialsDjango for Backend DevelopmentField Types & Relationships
Migrations & ORM Queries

Field Types & Relationships

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

11. ForeignKey (One-to-Many):
2 Author (1) ───────────< Articles (Many)
3 (Each article has one author; an author writes many articles)
4 
52. ManyToManyField (Many-to-Many):
6 Articles (Many) >───────< Tags (Many)
7 (An article has multiple tags; a tag belongs to multiple articles)
8 
93. OneToOneField (One-to-One):
10 User (1) ───────────── Profile (1)
11 (Each user has exactly one profile; each profile belongs to one user)

2. Implementing Relationships in Code

1# articles/models.py
2from django.db import models
3from django.conf import settings
4 
5class Category(models.Model):
6 name = models.CharField(max_length=100, unique=True)
7 slug = models.SlugField(unique=True)
8 
9 def __str__(self):
10 return self.name
11 
12class Tag(models.Model):
13 title = models.CharField(max_length=50, unique=True)
14 
15 def __str__(self):
16 return self.title
17 
18class Article(models.Model):
19 title = models.CharField(max_length=200)
20 body = models.TextField()
21 
22 # One-to-Many: Author relationship
23 author = models.ForeignKey(
24 settings.AUTH_USER_MODEL,
25 on_delete=models.CASCADE, # Delete articles if user is deleted
26 related_name="articles" # Reverse lookup: user.articles.all()
27 )
28 
29 # One-to-Many: Optional Category
30 category = models.ForeignKey(
31 Category,
32 on_delete=models.SET_NULL, # Keep article if category deleted, set FK to null
33 null=True,
34 blank=True,
35 related_name="articles"
36 )
37 
38 # Many-to-Many: Tags (creates bridge/junction table automatically)
39 tags = models.ManyToManyField(Tag, related_name="articles", blank=True)
40 
41 def __str__(self):
42 return self.title
43 
44class ArticleAnalytics(models.Model):
45 # One-to-One: Detailed telemetry attached to exactly one Article
46 article = models.OneToOneField(
47 Article,
48 on_delete=models.CASCADE,
49 related_name="analytics",
50 primary_key=True
51 )
52 bounce_rate = models.FloatField(default=0.0)
53 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 PolicyBehaviorBest Use Case
models.CASCADEAutomatically deletes all child records referencing the parent.User comments or invoice line items.
models.PROTECTRaises ProtectedError and blocks deletion if children exist.Deleting a Customer who has active orders.
models.SET_NULLSets the foreign key column to NULL (requires null=True).Deleting a department or optional category.
models.SET_DEFAULTSets the foreign key to its configured default value.Reassigning tickets to a default unassigned user.
models.DO_NOTHINGTakes 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:

1# Forward lookup (from child to parent):
2article = Article.objects.get(id=1)
3print(article.author.username)
4 
5# Reverse lookup (from parent to children):
6# Without related_name: user.article_set.all()
7# With related_name="articles":
8author_user = User.objects.get(username="dr_sumit")
9user_articles = author_user.articles.all() # Clean and expressive!

Interactive Quiz• Knowledge Check

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 LessonNext Lesson
Creating ModelsMigrations & ORM Queries

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext