I am using get_cached_trees()
method from django mptt library
As in the docs:
Takes a list/queryset of model objects in MPTT left (depth-first) order and caches the children and parent on each node. This allows up and down traversal through the tree without the need for further queries.
I am tracking db queries like this:
>>> from django.conf import settings
>>> settings.DEBUG = True
>>> from django.db import connection
>>> Model.objects.count()
>>> # python 3 uses print()
>>> print(len(connection.queries))
Taken from here.
Then I do
MyModel.objects.count()
print(len(connection.queries)) # 1
Then
first_object = MyModel.objects.first()
root_object = first_object.get_root()
print(len(connection.queries)) # 3
Then
cache = root_object.get_cached_trees()
print(len(connection.queries)) # 4
Then
cache[0].get_descendants()
print(len(connection.queries)) # 5
Why at the last step it gives me 5? It was supposed not to make a query to the DB.
You should have used get_children()
, it does not hit DB any extra time.
cache[0].get_children()
print(len(connection.queries)) # 4
In general, attributes that are cached: children
and parent