我已经通过谷歌搜索“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')
])
结果不符合分组标准!我明白了:
^{pr2}$我需要得到:
[{'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}]
有什么想法吗?在
多亏了PyCharm我才发现了这个问题。我真的不知道如果没有这个IDE我怎么能找到解决方案。我用得越多,我就越觉得它强大。然后我找到了一个解决方案:How can I remove Model Meta ordering in Django or get the original queryset from the built in Manager?
我的}。在
Request
模型有一个父级,它有一个字段date_creation
,还有一个class Meta:
,其中{因此,如果您不在查询中添加
order_by('field_xx')
,那么Django自动添加以下内容:order_by('date_creation')
。在因此,我的问题是:
它打破了质疑。在
解决办法是:
^{pr2}$实际上,我的解决方案从一开始就起作用了!在
以下是我的一个按小时分组的查询:
我的和你的区别在于我使用的是
^{pr2}$extra
函数。我想你应该做一些类似的事情,而不是你的第一个annotate
像这样:注意:我使用的是django1.9。在
编辑:我越看这个,也许我的计数中的
distinct=True
才真正起作用。在相关问题 更多 >
编程相关推荐