Reverse lookup in Django


In Django, reverse lookup refers to the process of accessing related objects in a database relationship from the "reverse" side. It allows you to retrieve objects that have a foreign key or many-to-many relationship with another object.


Let's consider an example to illustrate reverse lookup. Suppose you have two models in your Django application: `Author` and `Book`. An `Author` can have multiple books, and a `Book` can have only one author. Here's how the models might look:



from django.db import models

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

class Book(models.Model):
  title = models.CharField(max_length=100)
  author = models.ForeignKey(Author, on_delete=models.CASCADE)



With this setup, you can perform a reverse lookup to obtain all the books written by a specific author. Here's how you can achieve that:


author = Author.objects.get(name='John Doe')
books = author.book_set.all()


In the above code snippet, `author.book_set.all()` performs a reverse lookup on the `Author` model. The `book_set` attribute is automatically created by Django because `Book` has a foreign key relationship to `Author`. It represents all the books associated with the given author.


You can also use the related name parameter in the foreign key field to specify a custom name for the reverse lookup. Here's an updated example:



class Book(models.Model):
  title = models.CharField(max_length=100)
  author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')


With the `related_name` set to 'books', you can perform the reverse lookup like this:



author = Author.objects.get(name='John Doe')
books = author.books.all()


In this case, `author.books.all()` retrieves all the books associated with the given author.


Reverse lookup is a powerful feature in Django that allows you to traverse and access related objects from the "reverse" side of a relationship. It helps you retrieve related data efficiently and work with the connections between your models.


date:Aug. 8, 2023