如何在一个查询中计算一组答案的分数?

时间:2011-05-23 12:43:39

标签: django django-orm

我正在编写类似于Stackoverflow的webapp。如何查询问题并使用其分数对每个问题进行注释,这就是它有多少赞成票数减去它有多少下调票数。

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"),)

2 个答案:

答案 0 :(得分:1)

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()

答案 1 :(得分:0)

尽管DrTyrsa的回答是100%正确的。如果确实需要VOTE_CHOICES为'U'和'D',您可以在下面使用。

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