user3384985 user3384985 - 9 months ago 39
Python Question

How to get separate total amount of records for given list of ids in django

I am working with a question answer forum.

What I am trying to do this is pretty straightforward.

In questions list page, I want to show total number of answers a question have.

I know how to get all answers amount from a question record -

answer_records = Answer.objects.filter(question = question_record).count()

But, I want a single query which generates separate answer records amount for all given question records. So far I have tried -

answer_records = Answer.objects.filter(question__in = question_records).count()

It only generates single count of all question records.

Here is my model -

class Question(models.Model):
question_text = models.CharField(max_length = 500)
pub_date = models.DateTimeField('date published')
views = models.BigIntegerField(default = 0)
status = models.BooleanField(default = True)

def __str__(self):
return self.question_text

class Answer(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE, blank = True, null = True)
answer_text = models.TextField(default = '')
pub_date = models.DateTimeField(default =

def __str__(self):
return self.answer_text

How can I do that? Thanks for your help!

Answer Source

Here you want to do GROUP BY on questions and return the SUM of answers for each question. For achieving this, you may use .annotate() as:

Answer.objects.filter(question__in= question_records) \
    .values('question') \
    .annotate(question_count= Sum('question'))

Also take a look at Django's Document on "Generating aggregates for each item in a QuerySet". You will find it useful.