Django prefetch_相关性能 - to_attr 不适用于嵌套查找

问题描述 投票:0回答:1

我在django项目(v2.1.4)中有一个相对复杂的模型结构。比方说:

class Pizza(models.Model):
    pass

class ToppingPlacedOnPizza(models.Model):
    # Breaks a many-to-many relationship between Pizza and Topping and stores specific data
    # like the position of the topping in the pizza
    pizza = models.ForeignKey(Pizza, related_name='placed_toppings')
    topping = models.ForeignKey(Topping)
    # position ...

class Topping(models.Model):
    brand = models.ForeignKey(Brand)

class Brand(models.Model):
    name = models.CharField(max_length=32)

我需要检索为一组披萨中的每个披萨制作配料的所有品牌名称。说:

pizza1: brand1, brand2, brand3
pizza2: brand2, brand4
...

这样做,

prefetch_related
对于提高性能有很大帮助:

pizzas.prefetch_related('placed_toppings__topping__brand')

但是当查询大约 1000 个披萨时,它开始变得非常慢。 根据 this stackoverflow 答案,使用

Prefetch
类和
to_attr
可以提高性能,但我无法让它在我的情况下工作。由于嵌套查找,不清楚哪个对象
to_attr
将写入新属性。

我让

to_attr
在第一级工作。当设置
pizzas.prefetch_related(Prefetch('placed_toppings', to_attr('mytoppings')))
时,则
pizzas[0].mytoppings
存在。

但是设置

pizzas.prefetch_related(Prefetch('placed_toppings__topping__brand', to_attr('mybrands')))
时,不存在以下情况:

pizzas.mybrands
pizzas[0].mybrands
pizzas[0].placed_toppings.mybrands
pizzas[0].placed_toppings.first().mybrands
pizzas[0].placed_toppings.first().topping.mybrands

关于如何提高性能或使

to_attr
在嵌套查找上工作有什么想法吗?

python django prefetch
1个回答
0
投票

我做了这样的事情来实现这个目标

hospitals = hospitals_list.annotate(default_user_name=F("hospital_bookings__practice__default_user__first_name"))

您可以打印变量.查询。检查它的 SQL 查询。

print(hospitals.query)
© www.soinside.com 2019 - 2024. All rights reserved.