0

也许我搜索不正确,但我还没有找到这个......

我有三个模型。这里有两个,另一个是User模型:

class Comment(Model(20)):
    text = TextField(max_length=160)

class Look(Model(20)):
    comments = ManyToManyField(Comment, related_name='comments', editable=False)
    likes = ManyToManyField(get_user_model(), related_name="look_likes", editable=False)

现在我想按点赞数和评论数(Count(likes) + Count(comments))排序我的 Looks。

我试过了:

most_wanted = Look.objects.all()
most_wanted = most_wanted.annotate(count_comments=Count('comments'))
most_wanted = most_wanted.annotate(count_likes=Count('likes'))
most_wanted = most_wanted.extra(select = { 'count': 'count_comments + count_likes' })

但是带注释的字段不适用于额外的。我也试过:

most_wanted = Look.objects.all()
most_wanted = most_wanted.extra(select = { 'count': 'Count(comments) + Count(likes)' })

但是相关字段(来自ManyToMany)也不适用于extra。

有什么想法吗?

4

1 回答 1

0

您不能在查询中真正做到这一点。但似乎没有必要:这是一个简单的加法,可以在 Python 中完成。

于 2013-08-21T07:58:21.623 回答