如何计算一组答案?一次查询得分?
我正在编写一个类似于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
会让事情变得更容易:
will make it much easier:
虽然DrTyrsa的回答是100%正确的。如果确实需要 VOTE_CHOICES 为“U”和“D”,您可以使用以下内容。
Although DrTyrsa answer is 100% correct. You can use below if there is a real need for VOTE_CHOICES to be 'U' and 'D'.