Help with Aggregation / Annotation

14 views
Skip to first unread message

Alex G

unread,
Jun 3, 2016, 11:01:09 AM6/3/16
to Django users
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
Reply all
Reply to author
Forward
0 new messages