Django 2.0中的“ greatst-n-per-group”查询? [英] “greatest-n-per-group” query in Django 2.0?
问题描述
我基本上想做 this ,但使用Django 2.0。
Basically, I want to do this but with django 2.0.
如果我尝试:
Purchases.objects.filter(...。 。)。annotate(my_max = Window(
expression = Max('field_of_interest'),
partition_by = F('customer')
)
)
我返回所有行,但在每个记录中都添加了 my_max
属性。
I get back all the rows but with the my_max
property added to each record.
推荐答案
如果使用的是PostgreSQL:
If you are using PostgreSQL:
Purchases.objects.filter(.....).order_by(
'customer', '-field_of_interest'
).distinct('customer')
更新:过滤器中不允许使用窗口表达式,因此以下方法不起作用。请参阅此答案以获取最新解决方案
UPDATE: Window expressions are not allowed in filter, so following methods does not work. Please refer to this answer for up-to-date solution
或带有 Window
表达式
Purchases.objects.filter(.....).annotate(my_max=Window(
expression=Max('field_of_interest'),
partition_by=F('customer')
)
).filter(my_max=F('field_of_interest'))
但如果每个客户,后者可以产生多行它们具有相同的 field_of_interest
but latter can yield multiple rows per customer if they have the same field_of_interest
另一个 Window
,每个客户单行
Purchases.objects.filter(.....).annotate(row_number=Window(
expression=RowNumber(),
partition_by=F('customer'),
order_by=F('field_of_interest').desc()
)
).filter(row_number=1)
这篇关于Django 2.0中的“ greatst-n-per-group”查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!