views:

39

answers:

1

My code:

class School(models.Model): pass

class Student(models.Model):
    school = models.ForeignKey(School)
    TYPE_CHOICES = (
        ('ug', 'Undergraduate'),
        ('gr', 'Graduate'),
        ('al', 'Alumnus'),
    )
    type = models.CharField(max_length=2)

How do I obtain a QuerySet of Schools ordered by the number of Undergraduate Students?

A: 
from django.db.models import Count
School.objects.filter(student__type='ug').annotate(
                      num_students=Count('student')
                     ).order_by('num_students')

See the documentation on the relationship between aggregate and filter clauses.

Daniel Roseman
Please correct me if I'm wrong, but wouldn't this only return Schools with at least 1 undergrad student? Is there a way to sort all schools, first by number of Undergrads, then by number of Grads as a tiebreaker?
cloudshao
I'll accept this answer since it does answer my original question. Will ask my secondary question as a separate one. Thanks :-)
cloudshao