3
我們有兩個模型(簡化版本):如何預取Django中的聚合@property?
class Contestant(models.Model):
email = models.EmailField(max_length=255, unique=True)
# plus some other fields
@property
def total_points(self):
return self.points.aggregate(total=Sum('value'))['total'] or 0
class Points(models.Model):
contestant = models.ForeignKey(Contestant, related_name='points')
value = models.PositiveIntegerField()
# plus some other fields which determine based on what we
# awarded ``Points.value``
當我們展示選手與他們的total_points
值一起列表,它 導致每個結果的額外查詢 - 即執行以下查詢:
- 獲取參賽者的名單
- 取第一個選手
- 的
total_points
值取total_points
v第二個選手的ALUE - 等
我試圖改變查詢集預取數據,如下所示:
Contestant.objects.filter(...).prefetch_related('points')
...,但即使它的工作原理,預取的數據不被使用時 上市參賽者(因此每個結果仍嘗試在單獨的查詢中獲取total_points
)。
是否有可能:
- 某種方式告知ORM使用預取的值用於填充各個模型對象數據的@property字段時 (例如訪問
Contestant.total_points
@property方法內的預取的值)? - 或以不同的方式預取它們(與上面的例子相反)?
- 還是使用完全不同的方法實現相同的結果?
(我列出的結果tastypie
,如果它很重要。)
謝謝。
+1。謝謝,我也在大致思考這些問題。我需要檢查我們是否真的需要它。讓我們等待是否有人提出任何替代方案,但這似乎是我目前知道的最明智的方法。 – MicE
請注意,我們最後使用了https://github.com/initcrash/django-denorm(出於性能原因),但我接受這一點,因爲這是一種有效的方法。謝了哥們! – MicE
真棒,這個工程,但只使用* get_query_set *而不是* get_queryset * –