2011-02-02 95 views
10

我有一个Django模型,其中包含created时间戳,我希望获取每天创建的对象的计数。我希望在Django中使用聚合功能,但我无法弄清楚如何解决我的问题。假设这样做不起作用,我总是可以回到所有带有values_list的日期,但我更愿意将这些工作交给Django或DB。你会怎么做?从Django获取每日对象数

+1

http://stackoverflow.com/questions/2278076/count-number-of-records-by-date-in-django – 2011-02-02 21:50:40

回答

23

亚历克斯指出,在注释正确答案:

Count number of records by date in Django
幸得ara818

Guidoism.objects.extra({'created':"date(created)"}).values('created').annotate(created_count=Count('id'))

from django.db.models import Count 

Guidoism.objects \ 
    # get specific dates (not hours for example) and store in "created" 
    .extra({'created':"date(created)"}) 
    # get a values list of only "created" defined earlier 
    .values('created') 
    # annotate each day by Count of Guidoism objects 
    .annotate(created_count=Count('id')) 

我每天都在学习新的技巧阅读堆栈..真棒!

0

使用count方法:

YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count() 
+1

听起来有点昂贵,但每天计算虽然 – 2011-02-02 22:38:26