Django 2.0中的“ greatst-n-per-group”查询?

时间:2018-07-02 16:29:23

标签: django greatest-n-per-group

基本上,我想使用django 2.0来做this

如果我尝试:

Traceback (most recent call last): File "yeet.py", line 4, in <module> x = pyautogui.locateCenterOnScreen('yee.png') File "C:\Users\colem\AppData\Local\Programs\Python\Python37\lib\site-packages\pyscreeze\__init__.py", line 295, in locateCenterOnScreen coords = locateOnScreen(image, **kwargs) File "C:\Users\colem\AppData\Local\Programs\Python\Python37\lib\site-packages\pyscreeze\__init__.py", line 266, in locateOnScreen retVal = locate(image, screenshotIm, **kwargs) File "C:\Users\colem\AppData\Local\Programs\Python\Python37\lib\site-packages\pyscreeze\__init__.py", line 250, in locate points = tuple(locateAll(needleImage, haystackImage, **kwargs)) RuntimeError: generator raised StopIteration

我取回所有行,但是在每个记录中都添加了Purchases.objects.filter(.....).annotate(my_max=Window( expression=Max('field_of_interest'), partition_by=F('customer') ) )属性。

1 个答案:

答案 0 :(得分:3)

如果您使用的是PostgreSQL:

Purchases.objects.filter(.....).order_by(
    'customer', '-field_of_interest'
).distinct('customer')

或带有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

,则每个客户可以产生多行

另一个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)