Sobes.tech
Junior — Senior

How to get rid of N+1 queries in Django ORM

livecode

Task condition

It is necessary to improve the efficiency of database queries by avoiding unnecessary access to related models. The example below shows a simple schema with Author and Book models. The logic should be changed so that when displaying the author's name for a book, a separate query is not performed for each record.


from django.db import models

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

class Book(models.Model):
    name = models.CharField(max_length=255)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
    price = models.IntegerField(default=100)


all_books = Book.objects.all()

# Filtering books by authors
author_1_books = all_books.filter(author_id=1)
author_2_books = all_books.filter(author_id=2)


for book in all_books:
    print(book.author.name)