在 django 中一起使用 .annotate() 和 extra()
在制作查询集时,我似乎无法同时使用注释和额外功能 这
discussions = game.gamediscussion_set.filter(reply_to=None).annotate(up_votes = Count('userUpVotes'), down_votes=Count('userDownVotes')).extra(select={'votes':"'userUpVotes' - 'userDownVotes'"}).order_by('votes')
返回
Caught Warning while rendering: Truncated incorrect DOUBLE value: 'userUpVotes'
我想将 userUpVotes 和 userDownVotes 添加在一起以获得“投票”字段,然后按此字段排序。
userUpVotes 是用户的相关 ManyToManyField(userDownVotes 也是如此)。所以我需要先数一下这些。
有什么想法吗?
It seems i cannot use annotate and extra together when making a queryset
This
discussions = game.gamediscussion_set.filter(reply_to=None).annotate(up_votes = Count('userUpVotes'), down_votes=Count('userDownVotes')).extra(select={'votes':"'userUpVotes' - 'userDownVotes'"}).order_by('votes')
returns
Caught Warning while rendering: Truncated incorrect DOUBLE value: 'userUpVotes'
I want to add both userUpVotes and userDownVotes together to get a 'votes' field, then order by this field.
userUpVotes is a related ManyToManyField of users (as is userDownVotes). So i need to count these first.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将投票存储在同一个表或列中,则此类事情会容易得多,其中赞成票的值为 +1,反对票的值为 -1。您仍然可以通过简单的过滤器轻松计算赞成票或反对票的数量,通过简单的计数计算总票数,并通过总和计算总分。
用于将投票存储在单独的表中的示例代码。
total_score
将是一个字典:{'total': }This sort of thing is a lot easier if you store votes in the same table or column, with a value of +1 for an up vote and -1 for a down vote. You can still easily count the number of up or down votes with a simple filter, calculate the total number of votes with a simple count, and calculate the total score with the sum aggregate.
Sample code for storing votes in a separate table.
total_score
will be a dict: {'total': }