【问题标题】:Django ORM annotate with filterDjango ORM 使用过滤器进行注释
【发布时间】: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,谢谢!效果很好!!

标签: django orm annotate


【解决方案1】:

@Leistungsabfall 的建议

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

效果很好!

【讨论】:

  • 但是,它真的很慢。 :(
猜你喜欢
  • 1970-01-01
  • 2018-02-24
  • 2018-11-03
  • 2018-08-26
  • 1970-01-01
  • 2015-04-07
  • 2019-04-03
  • 1970-01-01
  • 2011-03-31
相关资源
最近更新 更多