2011-11-21 44 views
1

我需要從數據庫中獲得條目的評論數。我可以用django的評論框架嗎?我也使用未使用GenericForeignKeys我得到的分數條目這樣的投票應用:訂購條目通過意見計數與Django

class EntryManager(models.ModelManager): 
    def get_queryset(self): 
     return super(EntryManager,self).get_queryset(self).all().annotate(\ 
      score=Sum("linkvote__value")) 

但是,當有foreignkeys我被卡住。你有什麼想法嗎?

額外的解釋:我需要這樣獲取的條目:

id | body | vote_score | comment_score | 
1 | foo |   13 |    4 | 
2 | bar |   4 |    1 | 

這樣做之後,我可以通過comment_score訂購。 :)

Thans爲所有答覆。

+0

用comment_count = Count('comment')註釋不起作用? ..(你最好檢查註釋的數據庫字段是什麼..不知道django評論從內存.. – niklasdstrom

+0

不會知道它不會 –

+0

看看[這](https://github.com/coleifer/django-generic -聚合) – jperelli

回答

1

顯然,使用反向通用關係(或額外的過濾器,一般來說)的註釋仍然是open ticket(另請參閱corresponding documentation)。在此之前得到解決,我會建議使用在extra查詢原始的SQL語句,如:

return super(EntryManager,self).get_queryset(self).all().annotate(\ 
    vote_score=Sum("linkvote__value")).extra(select={ 
     'comment_score': """SELECT COUNT(*) FROM comments_comment 
      WHERE comments_comment.object_pk = yourapp_entry.id 
      AND comments_comment.content_type = %s""" 
    }, select_params=(entry_type,)) 

當然,你必須填寫正確的表名。此外,entry_type是一個「常數」,可你的查找功能外設置(見ContentTypeManager):

from django.contrib.contenttypes.models import ContentType 
entry_type = ContentType.objects.get_for_model(Entry) 

這是假設你有一個單一的模式Entry要計算您的分數。否則,事情會變得稍微複雜一點:您需要一個子查詢來獲取每個註釋對象類型的內容類型ID。