django aggregate or annotate

freethrow picture freethrow · Jan 5, 2012 · Viewed 43.3k times · Source

This is a very stupid thing, I know, but I just don't seem to get the handle on Django aggregate and annotate functions.

I have a very simple set of models: Events, Areas and Types. An event has foreign keys pointing to Area and Type. I would simply like to have the number of forthcoming events for any area and the same for any type, i.e. Area1 - 5 forthcoming events, Area2 - 6, or Type1 - 34 events and so on.

I would like to avoid writing custom SQL, and the q operator if possible.

Answer

c4urself picture c4urself · Jan 5, 2012

for a given area:

my_area = Area.objects.all()[0]
Event.objects.filter(area=my_area).count()

annotation

events = Event.objects.annotate(Count('area'))
for event in events:
    print event, event.area__count

or

events = Event.objects.annotate(count=Count('area'))
for event in events:
    print event, event.count

See the following docs:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate