【发布时间】:2017-07-13 15:23:04
【问题描述】:
我已经通过谷歌搜索“django group by month”阅读了这个 Django: Group by date (day, month, year) 和所有相关内容
如果我尝试“最干净”的解决方案 - 使用 Django 1.11,我最终会得到:
class Request(BaseModel):
date_creation = models.DateTimeField(default=None,
blank=True, null=True)
print([v for v in
Request.objects.annotate(month=ExtractMonth('date_creation'),
year=ExtractYear('date_creation'),)
.values('month', 'year')
.annotate(total=Count('month'))
.values('month', 'year', 'total')
])
结果并没有分组!我明白了:
[{'month': 6, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 1}]
我需要得到:
[{'month': 6, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 2}]
我也试过了:
print([v for v in
Request.objects.extra({'month': 'strftime("%m", date_creation)',
'year': 'strftime("%Y", date_creation)'})
.values('month', 'year')
.annotate(total=Count('*'))
.values('month', 'year', 'total')
])
然后我得到:
[{'month': '06', 'year': '2017', 'total': 1},
{'month': '07', 'year': '2017', 'total': 1},
{'month': '07', 'year': '2017', 'total': 1}]
有什么想法吗?
【问题讨论】: