How to reduce the number of calls to the database?select_related?

Do I understand correctly that:
cat = Category.objects.get(id=1)
In the template
cat.children.all()
cat.children.all()
cat.children.all()
cat.children.all()

There will be 4 calls to the database, and if so:
cat = Category.objects.select_related().get(id=1)
in the template
cat.children.all()
cat.children.all()
cat.children.all()
cat.children.all()

one or the other? Or am I mistaken?
July 9th 19 at 13:31
2 answers
July 9th 19 at 13:33
Solution
Wrong. In the first case there will be two treatment - getting the category when calling Category.objects.get(id=1) and getting its child elements on the first invocation of cat.children.all(), and all subsequent calls will be taken from the cache ORM. In the second select_related() will be ignored, as it is used for joins s, and you have children, most likely records from the same table. select_related() helps when you need to read the two related models in one query. This is all very straightforward and in detail described in the documentation.

Helps enlightenment view of sql queries after you are done queryset'AMI:
from django.db import connection
print(connection.queries)

Allows you to understand and how many of them were made, and what specific.
Viewing the sql queries are very lacking, did not know about this, thanks! - shani commented on July 9th 19 at 13:36
: try it https://github.com/django-debug-toolbar/django-deb... there in the first screenshot is just what You need, plus the ability to make explain request and execute the query directly in the database. Anyway - a lot of useful things - Jovanny.Wiza commented on July 9th 19 at 13:39
You can still configure logging to influence the development of consol derived SQL queries. If suddenly somewhere there was a bunch of queries at once seen. - Willow17 commented on July 9th 19 at 13:42
July 9th 19 at 13:35
Look at prefetch_related.

Find more questions by tags DjangoPython