Reverse relationship in Django
2 min readDec 25, 2020
This blog post teaches you about the relationship between the child and parent models and vice versa. Let us consider the following School and Student models for example.
The student model will have the student name and the school model will have the school name alone for simplicity.
This is how our models look like.
from django.db import models
class School(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='student')
def __str__(self):
return self.name
Direct relationship
In the above Student model, the school field has a foreign key relationship with the school model.
This is an example of a direct relationship. If we wish to get the school name from a student object we can simply do the following.
>>> from student.models import Student
>>> student = Student.objects.all().first()
>>> student
<Student: John>
>>> student.school.name
'Stanford'
Or if you want to query all the students whose school name is ‘Stanford’ we can simply do the following.