Table of contents
1.
Introduction
2.
Intermediate Models in Django
3.
Restrictions on the Intermediate Models in Django
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Intermediate models in Django

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.

This article will learn about intermediate models in Django. But what are these Intermediate models in Django? Intermediate models are associative models in any Many to Many(M2M) relationship between models in Django. Let's try to understand this with a detailed example. 

Intermediate Models in Django

In Django, a many-to-many relationship exists between models A and B, when one instance of model A is related to multiple instances of model B, and vice versa.

For example, an Exam and a Student share a many-to-many relationship in a school management system. One student can have multiple exams, and numerous students can take the same exam. However, there may be some valid field that neither belongs to the Exam nor Students, like date of exam, passing marks, etc. We include these fields inside the intermediate models in Django.

For our example, the code would look like this.

from django.db import models
 
class Exam(models.Model):
name = models.CharField(max_length = 128)
subject = models.CharField(max_length = 128)
 
def __str__(self):
     return self.name
 
class Student(models.Model):
name = models.CharField(max_length = 128)
class = models.IntegerField()
exam_taken = models.ManyToManyField(Exam, through = 'ExtraInfo')
 
def __str__(self):
     return self.name
 
class ExtraInfo(models.Model):
exam = models.ForeignKey(Exam, on_delete = models.CASCADE)
student = models.ForeignKey(Student, on_delete = models.CASCADE)
date_of_exam = models.DateField()
full_marks = models.IntegerField()
pass_marks = models.IntegerField()
You can also try this code with Online Python Compiler
Run Code

 

In the above code,

  • We made an Exam model to store the name and subject of the examination.
  • We created a Student model with fields: nameclass, and exam_taken fields.
  • Finally, we created the ExtraInfo model to store the intermediate fields. This intermediate model in Django has the following fields: date_of_examfull_marks, and pass_marks.
  • ForeignKey: When we set up the intermediary model, we explicitly specify foreign keys to the models related to the Many to Many relationships. This declaration defines how the two models are related.

 

Now, Let's create an instance of our ExtraInfo model by writing the following code.

exam_detail = Exam.objects.create(name= "Mid-Term Exam", subject= "English")
student_detail = Student.objects.create(name= "Abhishek", class= 12)
examination_info = ExtraInfo(exam= exam_detail, student= student_detail,
          date_of_exam = date(2022, 1, 1),
          full_marks = 100,
           pass_marks = 40)
 
examination_info.save()
You can also try this code with Online Python Compiler
Run Code

 

In the above code, we successfully created an instance for the ExtraInfo model and learned how to create intermediate models in Django.

Restrictions on the Intermediate Models in Django

We have a few restrictions on the intermediate models in Django:

  • The intermediate model must contain one - and only one - foreign key to the source model, or we must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.through. If more than one foreign key and through_fields are not specified, the validation error will be raised automatically. A similar restriction applies to the foreign key on the target model.
  • For a model with a many to many(M2M) relationship to itself through an intermediate model, foreign keys to the same model are allowed. Still, they will be treated as the different sides of the many-to-many relationships.  If we have more than two foreign keys, we must specify through_fields as above or raise a validation error.

Frequently Asked Questions

1. What are many to many relationships?

Ans. In Django, many to many relationships exist between two Django models if an instance of the first model is related to any instance of the second model and vice versa.

 

2. How do we add intermediate models in Django?

Ans. We add intermediate models in Django via through parameter in ManyToManyField. For Example: 

exam_taken = models.ManyToManyField(Exam, through = 'ExtraInfo')
You can also try this code with Online Python Compiler
Run Code

Key Takeaways

This article taught us about intermediate models in Django with a detailed example of a School Management System. We created an intermediate model to store the intermediate fields and created a mode instance.

Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass