Django:注释后合并查询集的问题

时间:2010-03-09 22:06:18

标签: django annotations django-queryset annotate

我有一个“Dialog”的经理看起来像这样:

class AnnotationManager(models.Manager):
def get_query_set(self):
    return super(AnnotationManager, self).get_query_set().annotate(
        num_votes=Count('vote', distinct=True),
        num_comments=Count('comment', distinct=True),
        num_commentators = Count('comment__user', distinct=True),
    )

投票和评论有一个ForeignKey to Dialog。评论有一个ForeignKey用户。当我这样做时:

dialogs_queryset = Dialog.public.filter(organization=organization)
dialogs_popularity = dialogs_queryset.exclude(num_comments=0) | dialogs_queryset.exclude(num_votes=0)

... dialogs_popularity永远不会返回组合,但只返回超过0条评论的对话框,或者如果我更改了OR的顺序,则对话框的票数超过0!

对我来说,预期的行为是获得超过0票的对话框以及超过0条评论的对话框。

我错过了什么?或者注释行为中是否存在错误?

1 个答案:

答案 0 :(得分:0)

是否想要同时拥有选票和评论的对话框?

# must have both a vote and a comment
# aka.  has_comments_and_votes = has_comments AND has_votes
#                              = !(has_no_comments OR has_no_votes)
has_comments = ~Q(num_comments=0)
has_votes = ~Q(num_votes=0)

dialogs_queryset.filter(num_comments__ne=0, num_votes__ne=0)
# or with Q objects
dialogs_queryset.filter(has_comments & has_votes)
dialogs_queryset.exclude(~has_comments | ~has_votes)

或者具有投票,评论或两者的对话框。 (基于评论你想要什么。)

# must have at least 1 vote or 1 comment
# aka. has_comments_or_votes = has_comments OR has_votes
#                            = !(has_no_comments AND has_no_votes)
dialogs_queryset.exclude(num_comments=0, num_votes=0)
# again with Q objects
dialogs_queryset.filter(has_comments | has_votes)  # easiest to read!
dialogs_queryset.exclude(~has_comments & ~has_votes)

我添加了Q objects示例,因为“|”在您的代码示例中似乎暗示了它们,并且它们使创建ORed查询变得更容易。

编辑: 我添加了has_commentshas_votes,以便更容易阅读。

相关问题