我的关系如下:
class Question(models.Model):
content = models.CharField(max_length=128)
class Answer(models.Model):
content = models.CharField(max_length=128)
question = models.ForeignKey(Question)
num_vote = models.IntegerField()
我想检索具有最大投票权的答案。我试过这个说法,但是不正确。
answers = Answer.objects.filter(question__exact=1).annotate(Max('num_vote'))
答案 0 :(得分:1)
预定义数量的答案?你需要,例如5个得分高的答案使用
answers = Answer.objects.filter(question=somequestion).order_by('-num_vote')[:5]
如果您需要max num_vote
的所有答案,则需要2次查询。
max_score = Answer.objects.filter(question=somequestion).aggregate(score=Max('num_vote'))
answers = Answer.objects.filter(question=somequestion, num_vote=max_score['score'])
答案 1 :(得分:0)
首先,如果您想获得特定Question
的所有答案,那么您必须使用Question
的实例:
question = Question.objects.get(...)
answers = Answer.objects.filter(question=question).annotate(Max('num_vote'))
其次,上述可能是您遇到问题的原因?