django aggregate or annotate
Thank you all very much. The problem I was having is documented in the last version, it is about the annotate and filter precedence.
areas = Area.objects.filter(event__in = eventQuery).annotate(num=Count('event'))
My error was in the fact that I was doing annotate first and filter second.
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
If you just need the total number of events for a single area, you don't need either annotate
or aggregate
, a simple count
will do:
Event.objects.filter(area=my_area).count()
If you want the count of events for multiple areas, you need annotate
in conjunction with values
:
Event.objects.values('area').annotate(Count('area'))