A
A
Animkim2016-05-17 13:05:20
Django
Animkim, 2016-05-17 13:05:20

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()

There will be 4 calls to the database, and if so:
сat = Category.objects.select_related().get(id=1)
в шаблоне
cat.children.all()
cat.children.all()
cat.children.all()
cat.children.all()

that one? Or I'm wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-05-17
@Animkim

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)

Allows you to understand how many of them were made, and which ones specifically.

U
un1t, 2016-05-18
@un1t

Look at prefetch_related.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question