Django查询:Count和Group BY

时间:2010-03-18 13:53:02

标签: sql django postgresql orm

我有一个查询,我正试图想出“django”的做法: 我想接听来自Call的最后100个电话。这很容易: calls = Call.objects.all()。order_by(' - call_time')[:100]

然而下一部分我找不到通过django的ORM做到这一点的方法。我想得到一个call_types的列表和每个人拥有的呼叫数量。我刚刚做了以前的查询集。通常我会做这样的查询:“SELECT COUNT(id),calltype FROM call WHERE id IN(SELECT id FROM call ORDER BY call_time DESC LIMIT 100)GROUP BY calltype;”

我似乎无法找到执行此特定查询的django方式。

以下是我的2个型号:

class Call( models.Model ):
    call_time = models.DateTimeField( "Call Time", auto_now = False, auto_now_add = False )
    description = models.CharField( max_length = 150 )
    response = models.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()

2 个答案:

答案 0 :(得分:1)

试试这个:

calls = Call.objects.all().order_by('-call_time')[:100]
types = CallType.objects.filter(call__in=calls).annotate(Count('call'))

您可能需要将distinct()添加到后一个查询集中。

答案 1 :(得分:0)

使用django 1.1.1这令人惊讶地无法工作;

from django.db.models import Count
calls = Call.objects.all().order_by('-call_time')[:100]
groups = calls.values('calltype').annotate(Count('calltype'))

它可以工作,但返回整个对象,而不仅仅是100个选中!不明白。

但是这种解决方法可能有所帮助(今天调用按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'))