How to easily perform reverse look up in django

Binge On Code
3 min readSep 15, 2021
How to easily perform reverse look up in django

This simple guide will tell you in a few words how to do reverse lookup in django. It makes your code cleaner and more predictable.

This simple reverse lookup in django tutorial is divided into two parts. The first part will focus on how to set your models right and the second part will give you the actual illustration of how to do the reverse lookup.

For this guide, we will be using hypothetical Mentor and Student models to demonstrate reverse lookup in django. In our case, each Student will be assigned to one Mentor, so we will have a many-to-one relation from Student to Mentor.

Defining models.

The first part, before we begin any django reverse lookup operation is to define the models. Our first model is the Mentor model.

class Mentor(models.Model):
"""
Our hypothetical mentor model. This is a mentor who can
guide and advice students.
"""

GENDER_CHOICES = (
('m', 'Male'),
('f', 'Female'),
('other', 'Other')
)

class Meta:
verbose_name = 'Mentor'
verbose_name_plural = verbose_name + 's'

name = models.CharField(max_length=100, blank=False, null=False)
gender = models.CharField(max_length=20, blank=False, null=False, choices=GENDER_CHOICES)

And as for the Student model, we will have this:

class Student(models.Model):
"""
Our hypothetical student model.

The assumption is that a student can have only one mentor at a time,
for the mentorship programme to be effective.

Also, for a student to exist in this mentorship programme, they must
have a mentor, and that means that if their mentor is, for some reason
not part of the mentorship programme any more, then the student will
be removed from the mentorship programme and they will need to be
registered once again under their new mentor.
"""

class Meta:
verbose_name = 'Student'
verbose_name_plural = verbose_name + 's'

mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=False, null=False)
student_id = models.CharField(max_length=20, blank=False, null=False)

Okay, we are almost ready with out models. So, now all we need to do is to simply set the django foreign key on the Student model in the right way.

What we need to do for django foreign key lookup to work is to simply change the mentor field on Student model to this:

mentor = models.ForeignKey(
Mentor,
on_delete=models.CASCADE,
related_name="student_mentor"
)

The important thing here is related_name. This is what we will be using to perform a django reverse lookup.

It’s value can be any string, but it is best to always have it as Model_Field format. This way, it will make more sense when doing the lookup, but it is up to you.

Now that we have updated our django foreign key on Student model, we are ready to proceed with making our lookup.

Performing reverse lookup in django.

Well, lets assume we have a view, where we want to get all the students who belong to a given mentor.

What I want you to understand is that with reverse lookup, shift your mindset and think in terms of the foreign model. That is as easy as it gets.

This is the first code snippet of how you would have done it without a reverse lookup.

def get_all_my_mentees_without_reverse_lookup(request):
"""
This is a hypothetical view, where a mentor needs to get a list of all
the mentees they are assigned to.

Normally, this is what you would have done without reverse lookup.
"""
mentor = request.user
mentees = Student.objects.filter(mentor=mentor)
return JSONResponse({mentees: mentees})

And now with reverse lookup in django, this is how you will do it.

def get_all_my_mentees_with_reverse_lookup(request):
"""
This is a hypothetical view, where a mentor needs to get a list of all
the mentees they are assigned to.

Now, with reverse lookup, thisis what we will have.
"""
mentees = request.user.student_mentor.all()
return JSONResponse({mentees: mentees})

Well, that is it! How simple was that!

Recap.

Well, to recap, in order to do a reverse lookup in django, you will need:

  • 1. To make your models ready for django foreign key lookup.
  • 2. Add a related_name to your child model.
  • 3. Use the related name to do the reverse lookup on your parent object.

As you can see, reverse lookup in django is a very important tip, as it makes your code cleaner on the long haul.

Conclusion.

Now you have an understanding of how to do a reverse lookup in django.

Well, that is it on this guide!

Happy coding!

Are you interested in learning Django? Checkout similar awesome articles on my website: Binge On Code > Django

--

--

Binge On Code

You love programming? Well, we do! We are a team of one as of now and are really passionate about programming and making the world better today than yesterday!