2

我有以下型號,藝術和ArtScore:Django的:時間範圍基於彙總查詢

class Art(models.Model): 
    title = models.CharField() 

class ArtScore(models.Model): 
    art = models.ForeignKey(Art) 
    date = models.DateField(auto_now_add = True) 
    amount = models.IntegerField() 

特定用戶操作導致的ArtScore項,比如當你點擊「我喜歡這門藝術」,我救一定量的ArtScore用於該藝術。

現在我試圖展示一個'本週最受歡迎'的頁面,所以我需要一個查詢僅聚合該時間範圍內的ArtScore金額。

我建立了下面的查詢,但它是有缺陷的......

popular = Art.objects.filter(
    artscore__date__range=(weekago, today) 
).annotate(
    score=Sum('artscore__amount') 
).order_by('-score') 

...因爲它只是排除了沒有日期範圍的ArtScore記錄藝術,但不排除ArtScore記錄日期範圍之外的記錄。

任何指針如何做到這一點將不勝感激!

感謝,

馬丁

回答

4

它看起來根據此類似: http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses你應該做你想要什麼。文檔錯了嗎?錯誤也許? 「

」第二個查詢將只包含 好書在註釋計數。「

的問候:

>>> Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book')) 

更改爲您查詢(忘了現在的順序):

Art.objects.filter(
    artscore__date__range=(weekago, today) 
).annotate(
    score=Sum('artscore__amount') 
) 

現在我們可以說

「的查詢將僅在註釋的中包含日期範圍內的artscores 總和「。

+0

你是對的,它確實起作用了......!謝謝! – Hoff 2009-11-13 18:32:01