Django ORM使用过滤器进行注释

时间:2015-12-08 10:11:08

标签: django orm annotate

我需要对特定群组中的用户进行发布或评论计数。

所以,我使用这段代码。效果很好。

if model == 'post':
    return _group.fbuser_set.filter(posts__group=_group).annotate(count=Count('posts')).order_by('-count')
else:
    return _group.fbuser_set.filter(comments__group=_group).annotate(count=Count('comments')).order_by(
                    '-count')

我希望获得有关特定群组中用户的帖子和评论数。

所以,我制作了这段代码

_group.user_set.filter(posts__group=_group, comments__group=_group) \
.annotate(p_count=Count('posts'), c_count=Count('comments'))

和这段代码。

_group.user_set.filter(posts__group=_group) \
.annotate(p_count=Count('posts')).filter(comments__group=_group) \
.annotate(c_count=Count('comments'))

但是,它们都不起作用。它的出局数是总数。

我可以做些什么才能获得特定群体的计数?

如果我需要使用原始sql,我怎样才能使sql具有相同的功能?

1 个答案:

答案 0 :(得分:0)

@Leistungsabfall的建议

_group.user_set.filter(posts__group=_group, comments__group=_group) \
            .annotate(p_count=Count('posts', distinct=True), c_count=Count('comments', distinct=True))

效果很好!

相关问题