Reverse relationship in Django

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.

Photo by Aditya Romansa on Unsplash
from django.db import models

class School(models.Model):
name = models.CharField(max_length=100)

def __str__(self):

class Student(models.Model):
name = models.CharField(max_length=100)
school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='student')

def __str__(self):

Direct relationship

In the above Student model, the school field has a foreign key relationship with the school model.

>>> from student.models import Student
>>> student = Student.objects.all().first()
>>> student
<Student: John>
>>> students = Student.objects.filter(school__name='Stanford')
>>> students
<QuerySet [<Student: John>]>

Reverse relationship

If we look at the models, it gives us a feeling that only child objects are mapped to the parent objects and not the other way round right?

>>> from student.models import Student, School
>>> School.objects.filter(student__name='John')
<QuerySet [<School: Stanford>]>
>>> from student.models import School
>>> School.objects.filter(student__name='John')
<QuerySet [<School: Stanford>, <School: Harvard>]>
student table record


Hope this article is helpful. Follow me for more articles on Django and Python. Happy coding!

Python Developer | Django Developer | Python Enthusiast