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.
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