如何使用django获取每天的对象数量?

时间:2010-04-28 23:48:49

标签: django

我有一个带有DateTimeField的django模型。

class Point(models.Model):
    somedata = models.CharField(max_length=256)
    time = models.DateTimeField()

我想计算每天这些物品的数量。我可以使用以下SQL查询执行此操作,但不知道如何通过django执行此操作。

SELECT DATE(`time`), Count(*)
FROM `app_point`
GROUP BY DATE(`time`)

能够将结果限制在日期范围内也会很好。

1 个答案:

答案 0 :(得分:3)

试试这个,

from django.db.models.sql.aggregates import Aggregate
from django.db.models import Count

class Day(Aggregate):
    """Custom aggregator
    """
    sql_function = 'DATE'
    sql_template = "%(function)s(%(field)s)"

    def __init__(self, lookup, **extra):
        self.lookup = lookup
        self.extra = extra

    def _default_alias(self):
        return '%s__%s' % (self.lookup, self.__class__.__name__.lower())
    default_alias = property(_default_alias)

    def add_to_query(self, query, alias, col, source, is_summary):
        super(Day, self).__init__(col, source, is_summary, **self.extra)
        query.aggregate_select[alias] = self

    q = Point.objects.annotate(day=Day('time')).annotate(found=Count('time')).values('day', 'found')
    # custom group by
    q.query.group_by = ["day"]

    print q
    # should return something like
    [{'found': 6, 'day': datetime.date(2010, 4, 30)}, 
     {'found': 4, 'day': datetime.date(2010, 5, 1)}, 
     {'found': 3, 'day': datetime.date(2010, 5, 2)}]

根据to this帖子,上述代码可能只适用于MySql数据库。