【发布时间】:2019-03-17 10:15:33
【问题描述】:
情况与Django prefetch_related children of children 相同,但问题不同:
我有一个模型Node,看起来像这样:
class Node(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, null=True)
一个节点可以有几个孩子,每个孩子都可以有自己的孩子。
我想做这样的事情:
def cache_children(node):
for child in node.children.all():
cache_children(child)
root_node = Node.objects.prefetch_related('children').get(pk=my_node_id)
all_nodes = Node.objects.all() # get all the nodes in a single query
# Currently: hit database for every loop
# Would like: to somehow use the already loaded data from all_nodes
cache_children(root_node)
由于我已经获取了all_nodes 查询中的所有节点,因此我想重用此查询中的缓存数据,而不是每次都执行一个新数据。
有什么方法可以实现吗?
【问题讨论】:
标签: django django-orm