1

我需要从数据库中获取包含评论数的条目。我可以用 django 的评论框架来做吗?我还使用了一个不使用 GenericForeignKeys 的投票应用程序,我得到的分数如下:

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

但是当有外键时,我被卡住了。你对此有什么想法吗?

额外说明:我需要获取这样的条目:

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

之后,我可以通过comment_score 订购它们。:)

感谢所有回复。

4

1 回答 1

1

显然,使用反向通用关系(或通常的额外过滤器)进行注释仍然是一个开放的票(另请参阅相应的文档)。在解决此问题之前,我建议在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。

于 2011-12-14T20:57:30.677 回答