23π
β
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
π€c4urself
21π
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'))
π€Daniel Roseman
- [Django]-What is actually assertEquals in Python?
- [Django]-Missing Table When Running Django Unittest with Sqlite3
- [Django]-Combining Django F, Value and a dict to annotate a queryset
3π
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.
π€freethrow
- [Django]-Images from ImageField in Django don't load in template
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-Django REST framework post array of objects
0π
Given the models Event and Area as:
from django.db.models import Count
class Area(models.Model):
area_name = models.CharField(...)
address = models.CharField(...)
class Event(models.Model):
event_name = models.CharField(...)
area = models.ForeignKey(Area,...)
In order to get the total number of events in each area, you can do:
area_query = Area.objects.filter(yourfilter)
total_event_per_area = Event.objects.filter(area__in=area_query).values('area').annotate(Count('id'))
print(total_event_per_area)
<QuerySet [{'area': 2, 'id__count': 2}, {'area': 4, 'id__count': 3}]>
π€7guyo
- [Django]-Error when using django.template
- [Django]-Images from ImageField in Django don't load in template
- [Django]-Django-Forms with json fields
Source:stackexchange.com