【问题标题】:Django prefetch_related children of childrenDjango prefetch_related children of children
【发布时间】: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

每次我尝试访问孩子的孩子时,数据库都会受到打击。

我怎样才能让它在单个数据库查询中获取节点、其子节点、其子节点的子节点等?

【问题讨论】:

标签: django django-orm


【解决方案1】:

根据docs,您可以这样做:

Restaurant.objects.prefetch_related('pizzas__toppings')

这将预取属于餐馆的所有比萨饼,以及属于这些比萨饼的所有配料。这将导致总共 3 个数据库查询 - 一个用于餐厅,一个用于比萨饼,一个用于浇头。

或者您可以使用 Prefetch 对象来进一步控制预取操作。

from django.db.models import Prefetch

Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name')))

【讨论】:

  • 我已经在我的问题中使用预取。我想知道的是我是否可以在单个数据库查询中获取所有内容。另外,在我的情况下,我可以在浇头上放浇头等,即使我不知道层次结构有多远,我也想全部获得。
  • @RyanPergent 你可以查看select_related:返回一个查询集,它将“遵循”外键关系,在执行查询时选择其他相关对象数据。这是一个性能提升器,它会导致单个更复杂的查询,但意味着以后使用外键关系将不需要数据库查询。 docs.djangoproject.com/en/2.1/ref/models/querysets/…
  • 是的,谢谢,但我已经调查过了。我可以使用 select_related 预取单个项目(如父项),但我不能使用它来获取子项列表。
  • @RyanPergent 你确定吗?文档中有一个示例:然后调用Book.objects.select_related('author__hometown').get(id=4) 将缓存相关的人员和相关的城市
  • 是的,但 author 和 hometown 是单个对象。例如,它不适用于 authors 和 cities 之类的列表。
猜你喜欢
  • 1970-01-01
  • 2017-11-29
  • 2013-01-15
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
相关资源
最近更新 更多