Friday, June 3, 2016

Help with Aggregation / Annotation

Hello all,

I know this is probably a really simple question, but I've been trying to solve it for ages now and keep failing!

I have two models:

class Subject(models.Model):
name = models.CharField(max_length=200)

class Pupil(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
active = models.BooleanField(default=0, db_index=True)
takes_subject = models.ManyToManyField(Subject)

Each pupil can take many subjects. Finding out how many pupils take each subject is easy, 
but I want to find out how many pupils take multiple subjects. Something like:

Subjects taken |  Number of pupils
===============|==================
4              |  20
3              |  15
2              |  7
1              |  38

That way I can know that say 15 pupils are taking 3 subjects while 38 pupils are taking 1 subject. 

How do I achieve this?

Thanks in advance,

Alex

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9698832a-6f0a-45d4-ae13-ee1c9ca918ee%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment