你可以用
TruncWeek
和
TruncYear
:
from django.db.models.functions import TruncWeek, TruncYear
count_for_week = myModel.objects.annotate(
week=TruncWeek('created_at'),
).values(
'week',
).annotate(
count=Count('id'),
)
count_for_year = myModel.objects.annotate(
year=TruncYear('created_at'),
).values(
'year',
).annotate(
count=Count('id'),
)
因此,您将拥有:
<QuerySet [{'week': datetime.datetime(2019, 2, 18, 0, 0, tzinfo=<UTC>), 'count': 1}]>
在哪里?
week
或
year
值将是该范围的开始日期时间:一年中的一周
你可以在Django文档中阅读更多细节
here
.