python - Django:多个annotate()中的Count()
问题描述
我有一个带有ForumPost
, ForumComment
, ForumPostLike
,ForumCommentLike
模型的 Django 项目。帖子有多个评论,多个论坛帖子喜欢。评论有多个论坛评论喜欢。每个用户只能赞一次帖子或评论。
我想要什么:我想通过以下方式订购帖子calculated = (num_comments*5 + num_postlikes + num_commentlikes)
问题:使用以下代码,似乎我得到了我想要的。但是有一些奇怪的行为Count()
。另外,我想知道是否有更好的方法来实现我的目标。
模型.py
class ForumPost(models.Model):
# author, title .. etc.
class ForumComment(models.Model):
post = models.ForeignKey(ForumPost, on_delete=models.CASCADE, related_name='comments')
#other fields
class ForumPostLike(models.Model):
liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='liked_forumposts')
post = models.ForeignKey(ForumPost, on_delete=models.CASCADE, related_name='forumpostlikes')
class ForumCommentLike(models.Model):
liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='liked_forumcomments')
comment = models.ForeignKey(ForumComment, on_delete=models.CASCADE, related_name='forumcommentlikes')
视图.py
posts= ForumPost.objects.filter(published_date__lte=timezone.now()).\
prefetch_related('comments', 'forumpostlikes')
posts_top = posts\
.annotate(num_commentlikes=Count('comments__forumcommentlikes__liker'))\
.annotate(num_postlikes=Count('forumpostlikes', distinct=True))\
.annotate(num_comments=Count('comments', distinct=True))\
.annotate(calculated=(F('num_comments')*Value(5)) + F('num_postlikes') +F('num_commentlikes')*Value(0.5))\
.order_by('-calculated')
Count() 的奇怪行为:
annotate(num_commentlikes=Count('comments__forumcommentlikes__liker'))
使用此代码,我想从与当前帖子相关的所有评论中获取喜欢的总数。但结果显示2*correct number。一旦我意识到这一点,我将这个数字乘以Value(0.5)
反映正确的数字。
如果我使用 distinct 如下:
annotate(num_commentlikes=Count('comments__forumcommentlikes__liker', distinct=True))
此代码仅给我来自第一条评论的点赞数。
为什么会这样?另外,如何改进我的代码?谢谢!
解决方案
推荐阅读
- php - 我正在尝试使用 PHP 和 mysql 制作点击计数器
- java - 当订阅者在 rxjava 中抛出异常时如何继续处理?
- angular - 开发和生产中快照组件名称的不同值
- c# - 数组 Mvc 控制器到 JavaScript
- mongodb - 如何根据不同情况应用/选择 getPlanCache() 和 hint()
- javascript - 如何在 async.parallel 方法中使异步代码同步 - NodeJs
- awk - 在 bash 中编辑文件的标题
- angularjs - 无法解析 ModalPage 的所有参数:([object Object], [object Object], ?, [object Object])
- python - 如何理解python中的id()?
- java - 当有两个相同的名称和不同的类 bean 时如何按名称获取正确的 bean