Django query: Count and Group BY
I have a query that I'm trying to figure the "django" way of doing it: I want to take the last 100 calls from Call. Which is easy: calls = Call.objects.all().order_by('-call_time')[:100]
However the next part I can't find the way to do it via django's ORM. I want to get a list of the call_types and the number of calls each one has WITHIN that previous queryset i just did. Normally i would do a query like this: "SELECT COUNT(id),calltype FROM call WHERE id IN ( SELECT id FROM call ORDER BY call_time DESC LIMIT 100 ) GROUP BY calltype;"
I can't seem to find the django way of doing this particular query.
Here are my 2 models:
class Call( models.Model ):
call_time = models.DateTimeField( "Call Time", auto_now = False, auto_now_add = False )
description = models.CharField( max_length = 150 )
response = mod开发者_Python百科els.CharField( max_length = 50 )
event_num = models.CharField( max_length = 20 )
report_num = models.CharField( max_length = 20 )
address = models.CharField( max_length = 150 )
zip_code = models.CharField( max_length = 10 )
geom = models.PointField(srid=4326)
calltype = models.ForeignKey(CallType)
objects = models.GeoManager()
class CallType( models.Model ):
name = models.CharField( max_length = 50 )
description = models.CharField( max_length = 150 )
active = models.BooleanField()
time_init = models.DateTimeField( "Date Added", auto_now = False, auto_now_add = True )
objects = models.Manager()
try this:
calls = Call.objects.all().order_by('-call_time')[:100]
types = CallType.objects.filter(call__in=calls).annotate(Count('call'))
you might need to add distinct() to the latter queryset though.
With django 1.1.1 this surprisingly doesnt work ;
from django.db.models import Count
calls = Call.objects.all().order_by('-call_time')[:100]
groups = calls.values('calltype').annotate(Count('calltype'))
it works but returns on the whole objects, not only the 100 selected! cant understand.
but this workaround could help (today calls summary grouped by calltype) :
import datetime
Call.objects.order_by('-call_time').filter(call_time__gte=datetime.datetime.today() - datetime.timedelta(days=1)).values('calltype').annotate(Count('calltype'))
精彩评论