2013-03-11 33 views
0

非常簡單...我使用的是Django 1.4.1,並且需要通過其上的註釋數量的倒數來排序查詢集。我正在使用Django評論框架,並試圖使用其他答案中推薦的.annotate(comment_count = Count('comment')結構...我得到'評論'並不能解決字段錯誤。Django:通過評論計數設置的訂單查詢

我也試過0.3.1版本Django的通用骨料,這將引發一個數據庫錯誤,讓出去了。

Photo.objects.filter(galleries=gallery).annotate(comment_count=Count('comments')).order_by('-comment_count')[(page-1)*RESULTS_PER_PAGE:page*RESULTS_PER_PAGE] 

有什麼建議?

+0

請用'Photo'模型 – 2013-03-11 02:59:43

+0

的相關內容我很困惑更新您的問題...的評論系統建立到Django的。它附加到任何模型。照片模型結構本身是不相關的,我也可以嘗試通過評論數量來訂購Widgets。 – 2013-03-11 11:07:07

+0

忽略我的評論。我沒有意識到評論應用程序使用'GenericForeignKey',因此不需要與您的'Photo'模型相關的明確引用。你可能會發現你正在嘗試做的事情目前不可能。見[這裏](https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations-and-aggregation) – 2013-03-11 11:52:44

回答

0

把功能下的照片模式

class Photo(models.Model): 
    ......... 

    def orders(self): 
     //filter first the highest count of comments 
     aggregate = Photo.objects.aggregate(comment_count=Count('comments')) 
     return aggregate['comment_count'] + 1 

然後,你可以這樣調用鑑於:

comments = Photo.objects.filter(galleries=gallery).orders() 
+0

謝謝你的答案凱瑟琳!我很困惑,但我試圖通過comment_count命令我的查詢集...這種方法會這樣做嗎? (是命令一個神奇的方法名稱?) – 2013-03-11 11:09:52

+0

我有一個徽章模型,我需要基於點獲得用戶的排名,所以我這樣做,它的工作原理。我不知道在你身邊,只是嘗試。如果不工作,我們會嘗試另一個,直到你的問題得到解決:) – catherine 2013-03-11 11:13:48