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()
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: name, class, 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_exam, full_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()
In the above code, we successfully created an instance for the ExtraInfo model and learned how to create intermediate models in Django.




