Conteúdo do Curso
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Minimazing Database Hints
Efficient database interaction is crucial in web development to enhance performance and reduce server load. Django ORM offers two powerful tools, select_related and prefetch_related, to optimize database queries by minimizing the number of database hits.
The N+1 Query Problem
Consider the scenario where you want to list all books along with their genres' formats. A naive approach might look like this:
In this case, for each book, a separate query is made to fetch its associated genre's format. So, if you have N books, this will result in 1 query to fetch all books (the "1" in N+1) and N additional queries to fetch each book's author (the "N" in N+1). If we have 100 books, we will made 101 queries to the Database, but 100 is too small number for a bookstore site😉. This is highly inefficient and can significantly impact performance, especially with a large dataset.
Understanding select_related
select_related is used for forward ForeignKey and OneToOneField relationships. It performs an SQL join and includes the fields of the related object in the SELECT statement. This is ideal for reducing the number of queries when you know you'll need the related objects.
In summary, the entire operation will perform exactly one SQL query to the database.
Understanding prefetch_related
prefetch_related, on the other hand, is used for ManyToManyField, reverse ForeignKey, and generic relations. It performs separate queries and joins them in Python. This is useful for situations where select_related is not applicable or efficient.
This results in two queries irrespective of the number of authors or books, significantly reducing database hits.
Obrigado pelo seu feedback!