Group objects by dates

安稳与你 提交于 2019-12-25 07:58:05

问题


clicks = SellerClick.objects.extra({'date' : "date(timestamp)"}).values('date').annotate(count=Count('timestamp'))

The model has a datetime field called timestamp that was are using. I first, convert the datetime field to just a date field. Then the rest is guessing. I need to group by, and then count how many objects are of each date.

So the desired result would be a date, then a count, based on how many objects have that date in the timestamp field.


回答1:


I prefer to use annotate over extra

from django.db.models.expressions import RawSQL  

SellerClick.objects.annotate(
    date=RawSQL('date(date_joined)',[]),
).values('date').annotate(count=Count('date')))



回答2:


You've got everything but an initial queryset there. The extra sql you're passing doesn't include a select so you need to give it something to act on.

clicks = SellerClick.objects.all()
    .extra({'date' : "date(timestamp)"})
    .values('date')
    .annotate(count=Count('timestamp'))

Ref: StackOverflow: Count number of records by date in Django



来源:https://stackoverflow.com/questions/37152402/group-objects-by-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!