Django mptt get_cached_trees() 命中数据库
Django mptt get_cached_trees() hits database
我正在使用 django mptt library
中的 get_cached_trees()
方法
如文档中所示:
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.
我正在跟踪这样的数据库查询:
>>> from django.conf import settings
>>> settings.DEBUG = True
>>> from django.db import connection
>>> Model.objects.count()
>>> # python 3 uses print()
>>> print(len(connection.queries))
摘自 here.
那我就
MyModel.objects.count()
print(len(connection.queries)) # 1
然后
first_object = MyModel.objects.first()
root_object = first_object.get_root()
print(len(connection.queries)) # 3
然后
cache = root_object.get_cached_trees()
print(len(connection.queries)) # 4
然后
cache[0].get_descendants()
print(len(connection.queries)) # 5
为什么在最后一步它给了我 5?应该不会查询数据库。
你应该用过get_children()
,它没有任何额外的时间命中数据库。
cache[0].get_children()
print(len(connection.queries)) # 4
通常,缓存的属性:children
和 parent
我正在使用 django mptt library
中的get_cached_trees()
方法
如文档中所示:
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.
我正在跟踪这样的数据库查询:
>>> from django.conf import settings
>>> settings.DEBUG = True
>>> from django.db import connection
>>> Model.objects.count()
>>> # python 3 uses print()
>>> print(len(connection.queries))
摘自 here.
那我就
MyModel.objects.count()
print(len(connection.queries)) # 1
然后
first_object = MyModel.objects.first()
root_object = first_object.get_root()
print(len(connection.queries)) # 3
然后
cache = root_object.get_cached_trees()
print(len(connection.queries)) # 4
然后
cache[0].get_descendants()
print(len(connection.queries)) # 5
为什么在最后一步它给了我 5?应该不会查询数据库。
你应该用过get_children()
,它没有任何额外的时间命中数据库。
cache[0].get_children()
print(len(connection.queries)) # 4
通常,缓存的属性:children
和 parent