Junior — Senior
Counting the number of database queries in Django ORM
livecode
Task condition
Determine how many SQL queries will be sent to the database when executing the following operations in Django ORM.
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)
# Get a QuerySet with all books
books_qs = Book.objects.all()
# Filter books by the first author
books_by_author1 = books_qs.filter(author_id=1)
# Filter books by the second author
books_by_author2 = books_qs.filter(author_id=2)
Analyze which queries will be executed when creating books_qs and for each of the filters.