注释 Sum 会导致 None 而不是零
我正在制作一个与您现在所在的页面类似的质量检查网站。我试图按分数对答案进行排序,但没有投票的答案的分数设置为“无”而不是 0。这会导致页面底部没有投票的答案位于负排名答案的下方。当没有人对答案投票时,如何使注释分数为零?
这是我的模型:
from django.contrib.auth.models import User
Answer(models.Model):
//some fields here
pass
VOTE_CHOICES = ((-1, Down), (1, Up))
Vote(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)
type = models.IntegerField(choices = VOTE_CHOICES)
class Meta:
unique_together = (user, answer)
这是我的查询:
answers = Answer.objects.filter(<something here>)
.annotate(score=Sum('vote__type'))
.order_by('-score')
编辑: 需要明确的是,我想在查询中执行此操作。我知道我可以将它变成一个列表,然后在我的 python 代码中对其进行排序,但如果可能的话我想避免这种情况。
I'm making a QA site that is similar to the page you're on right now. I'm attempting to order answers by their score, but answers which have no votes are having their score set to None rather than 0. This results in answers with no votes being at the bottom of the page below negatively ranked answers. How can I make the annotated score be zero when there are no votes for an answer?
Here's my model:
from django.contrib.auth.models import User
Answer(models.Model):
//some fields here
pass
VOTE_CHOICES = ((-1, Down), (1, Up))
Vote(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)
type = models.IntegerField(choices = VOTE_CHOICES)
class Meta:
unique_together = (user, answer)
And here's my query:
answers = Answer.objects.filter(<something here>)
.annotate(score=Sum('vote__type'))
.order_by('-score')
edit: And to be clear, I'd like to do this in the query. I know I could turn it into a list and then sort it in my python code, but I'd like to avoid that if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Coalesce
函数< /a> 来自 django.db.models.functions ,例如:You can use the
Coalesce
function fromdjango.db.models.functions
like:来自 django 的 Coalesce 文档:
因此,我们可以使用“默认”参数,而不是使用
Coalesce
:from django's documentation for Coalesce:
So instead of using
Coalesce
, we can use the "default" argument:您使用自定义
Manager
怎么样?例如:那么,您可以使用:
What about you use custom
Manager
? For example:Then, you can use: