【发布时间】:2021-10-15 11:02:21
【问题描述】:
Django docs on aggregation 给出以下注释示例:
for store in Store.objects.all():
store.min_price # Error! min_price not defined!
for store in Store.objects.annotate(min_price=Min('books__price')):
store.min_price # Fine
但是,我们只注释了一个字段。我们只知道最便宜的书价格是多少,但不知道哪本书是最便宜的书。如果我希望注释的结果恰好是那本书,而不仅仅是它的价格呢? (我会调用这个函数或类AggregateRelation)
for store in Store.objects.annotate(
cheapest_book=AggregateRelation('books__price', Min)
):
store.cheapest_book.price
store.cheapest_book.title
有没有办法做到这一点?
我检查了FilteredRelation,但这仅对过滤有用。它不会真正检索实例。
【问题讨论】:
-
好吧,如果 SQL 中有方法,您可以运行原始 SQL 查询。我知道这可能不是您想要的。
标签: sql django annotations