Performance: Database query optimization with select_related
This affects the speed of database queries and reduces the number of queries sent to the database, improving page load time.
Jump into concepts and practice - no test required
books = Book.objects.select_related('author').all() for book in books: author_name = book.author.name # no extra queries
books = Book.objects.all() for book in books: author_name = book.author.name # triggers a query per book
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without select_related | N/A | N/A | Blocks rendering waiting for multiple queries | [X] Bad |
| With select_related | N/A | N/A | Faster rendering due to fewer queries | [OK] Good |
select_related in Django queries?select_related doesselect_related is used to fetch related objects in a single database query by joining tables.select_related to fetch related author objects in a Book model query?select_related is a queryset method that takes related field names as string arguments inside parentheses.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)books = Book.objects.select_related('author').all()
for book in books:
print(book.author.name)select_related('author') fetches books and their related authors in one query.book.author.name for each book, showing author names without extra queries.books = Book.objects.select_related('publisher').all()Book has no publisher foreign key field.Book has no publisher foreign key, this field does not exist.select_related raises a FieldError.class Publisher(models.Model):
name = models.CharField(max_length=100)
class Author(models.Model):
name = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)author and the publisher related to that author in one query.select_related syntaxselect_related('author', 'author__publisher') to join both foreign keys in one query.publisher is not directly on Book. Book.objects.prefetch_related('author', 'author__publisher').all() uses prefetch_related which is less efficient here. Book.objects.select_related('publisher').all() misses author relation.