Answer the question
In order to leave comments, you need to log in
How to reduce the number of database calls?select_related?
Do I understand correctly that:
сat = Category.objects.get(id=1)
В шаблоне
cat.children.all()
cat.children.all()
cat.children.all()
cat.children.all()
сat = Category.objects.select_related().get(id=1)
в шаблоне
cat.children.all()
cat.children.all()
cat.children.all()
cat.children.all()
Answer the question
In order to leave comments, you need to log in
You are wrong. In the first case, there will be two calls - getting the category when calling Category.objects.get(id=1) and getting its children on the first call to cat.children.all(), and all subsequent calls will be taken from the ORM cache. In the second select_related() will be ignored, since it is used for joins, and your children, most likely, are records from the same table. select_related() helps when you need to read data from two related models in one query. All this is very simple and is described in detail in the documentation .
It helps a lot to enlighten the view of the made sql queries after operations with querysets:
from django.db import connection
print(connection.queries)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question