也许我没找对,但我还没找到呢......
我有三个型号 . 这里有两个,另一个是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(评论))来命令我的外观 .
我试过了:
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)也无法使用额外的字段 .
有没有?
1 回答
你不能在查询中真正做到这一点 . 但似乎没有必要:它是一个简单的添加,它可以在Python中完成 .