1

I have a model like this:

class Question(models.Model):
  #something

class Answer(models.Model):
  question = models.ForeignKey(Question)      
  points_achieved = models.PositiveSmallIntegerField()

Now I want to query for the distribution of points_achieved: For each question I want to know how many scored 0 points, 1 points, etc. In python I would do this as follows:

dists = []
  for q in Question.objects.all():
    dist = defaultdict(int)
    for answer in q.answer_set.all():
      dist[answer.points_achieved]+=1
    dists.append(dist)

How can I accomplish the same using Django's querying methods?

2 Answers 2

3

Try this

from django.db.models import Count
Answer.objects.all().values('question', 'points_achieved').annotate(total=Count('points_achieved')).order_by('total')

Source: Django Aggregation

1
  • Thank you, just found the (almost) same solution just now :-)
    – Daniel
    Mar 24, 2015 at 22:48
0

After some more wild-guessing and following this tutorial, I managed to come up with this solution:

Answer.objects.values('question','points_achieved')
  .annotate(Count('points_achieved'))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.