如何计算一组答案?一次查询得分?

发布于 2024-11-09 08:13:51 字数 482 浏览 3 评论 0原文

我正在编写一个类似于 Stackoverflow 的网络应用程序。我如何查询问题并用其分数注释每个问题,这只是它的赞成票数减去它的反对票数。

class Question(models.Model):
    pass

class Answer(models.Model):
    pass

VOTE_CHOICES = (
    ('U', 'Up'),
    ('D', 'Down'),
)

class Vote(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    type = models.CharField(max_length=1, choices=VOTE_CHOICES, db_index=True) 

    class Meta:
        unique_together = (("user", "answer"),)

I am writing a webapp similar to Stackoverflow. How can I query Questions and annotate each question with its score, which is simply how many upvotes it's has minus how many downvotes it's had.

class Question(models.Model):
    pass

class Answer(models.Model):
    pass

VOTE_CHOICES = (
    ('U', 'Up'),
    ('D', 'Down'),
)

class Vote(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    type = models.CharField(max_length=1, choices=VOTE_CHOICES, db_index=True) 

    class Meta:
        unique_together = (("user", "answer"),)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

dawn曙光 2024-11-16 08:13:51
VOTE_CHOICES = (
    (1, 'Up'),
    (-1, 'Down'),
)

会让事情变得更容易:

# q - your question
Vote.objects.filter(answer__question=q).aggregate(Sum('type'))

# all questions annotated
Vote.objects.values('answer__question_id').annotate(score=Sum('type')).order_by()
VOTE_CHOICES = (
    (1, 'Up'),
    (-1, 'Down'),
)

will make it much easier:

# q - your question
Vote.objects.filter(answer__question=q).aggregate(Sum('type'))

# all questions annotated
Vote.objects.values('answer__question_id').annotate(score=Sum('type')).order_by()
胡渣熟男 2024-11-16 08:13:51

虽然DrTyrsa的回答是100%正确的。如果确实需要 VOTE_CHOICES 为“U”和“D”,您可以使用以下内容。

votes = Vote.objects.filter(answer__question=q)
rank = votes.filter(type='U').count() - votes.filter(type='D').count()

Although DrTyrsa answer is 100% correct. You can use below if there is a real need for VOTE_CHOICES to be 'U' and 'D'.

votes = Vote.objects.filter(answer__question=q)
rank = votes.filter(type='U').count() - votes.filter(type='D').count()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文