2

I have the relationship follow as:

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

I want to retrieve the answers, which have the max voting. I tried this statement but it isn't correctly.

answers = Answer.objects.filter(question__exact=1).annotate(Max('num_vote'))

2 Answers 2

1

Some predefined number of answers? You you need e.g. 5 high-scored answers use

answers = Answer.objects.filter(question=somequestion).order_by('-num_vote')[:5]

If you need all the answers with max num_vote you need 2 queries.

max_score = Answer.objects.filter(question=somequestion).aggregate(score=Max('num_vote'))
answers = Answer.objects.filter(question=somequestion, num_vote=max_score['score'])
Sign up to request clarification or add additional context in comments.

Comments

0

First, if you want to get all answers for a specific Question, then you have to use an instance of the Question:

question = Question.objects.get(...)
answers = Answer.objects.filter(question=question).annotate(Max('num_vote'))

Second, the above may be the reason for your problems?

1 Comment

Thank Joachim Pileborg. But I want to retrieve the answers that have the max num_vote. E.g. There are 3 answers. Answer 1 has 3 num_vote. Answer 2 has 1 num_vote and Answer 3 has 3 num_vote. So, the result is <Answer1, Answer3>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.