【发布时间】:2015-12-08 10:11:07
【问题描述】:
我需要获取特定组中用户的帖子或评论数。
所以,我使用此代码。效果很好。
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?
【问题讨论】:
-
尝试将
distinct=True添加到您的计数中,如下所示:.annotate(p_count=Count('posts', distinct=True)) -
@Leistungsabfall,谢谢!效果很好!!