参考:http://python.usyiyi.cn/django/topics/db/aggregation.html
from django.db.models import Count today = datetime.datetime.now()
p1 = datetime.timedelta(days=1)
users_today = lockoutusers.objects.filter(lockouttime__range=[(today-p1).date(),(today+p1).date()]) #获取当天的item记录 users_today.values('sAMAccountName').annotate(num=Count('sAMAccountName')) #对sAMAccountName字段进行分组,并得出个数
返回结果:
[{'num': 1, 'sAMAccountName': u'zhongwenming'}, {'num': 1, 'sAMAccountName': u'sunqian'},...(remaining elements truncated)...']
假设有以下 model:
class Foobar(models.Model):
name = models.CharField(max_length=100)
date_created = models.DateField(auto_now_add=True) def __unicode__(self):
return self.name
按天统计数量的代码如下:
from django.db import connection
from django.db.models import Count select = {'day': connection.ops.date_trunc_sql('day', 'date_created')}
Foobar.objects.extra(select=select).values('day').annotate(number=Count('id'))
# [{'number': 10, 'day': datetime.datetime(2013, 9, 29, 0, 0, 0}]