【发布时间】:2019-08-07 15:40:30
【问题描述】:
我有一个模型Node,看起来像这样:
class Node(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE)
一个节点可以有几个孩子,每个孩子都可以有自己的孩子。
如果我这样做:
def show_child(node):
for child in node.children.all():
show_child(child)
root_node = Node.objects.prefetch_related('children').get(pk=my_node_id) # hit database twice, as expected
print("Now testing queries")
root_node.children.all() # no hit
root_node.children.all() # no hit
root_node.children.all() # no hit
root_node.children.all() # no hit
print("Test 2")
show_child(root_node) # hit database for every loop except the first
每次我尝试访问孩子的孩子时,数据库都会受到打击。
我怎样才能让它在单个数据库查询中获取节点、其子节点、其子节点的子节点等?
【问题讨论】:
-
设法使其与另一种方法一起使用:stackoverflow.com/questions/55205973/…
标签: django django-orm