Get count using annotate

11 views
Skip to first unread message

karan

unread,
Jul 19, 2012, 12:00:45 PM7/19/12
to django...@googlegroups.com
Hi,

my models is-

class Students(models.Model):
        country = models.ManyToManyField( Country )

I want to calculate the total number of student objects for each of the country objects.

I need the count of students interested in each country so far in my database.

I was trying something with annotate but couldnt get far.

I need suggestions :)

Thanks . cheers !

Tom Evans

unread,
Jul 19, 2012, 12:21:20 PM7/19/12
to django...@googlegroups.com
Country.objects.annotate(num_students=Count('students'))

https://docs.djangoproject.com/en/1.4/topics/db/aggregation/#cheat-sheet

FYI: Your class name should be singular, as anything that 'Students'
has a foreign key to would access the related student instances by
'foo_object.studentss_set' (note the double s).

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages