Django group按月份和年份划分

2024-04-20 07:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经通过谷歌搜索“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}]

有什么想法吗?在


Tags: djangointruefordatebyobjectsrequest
2条回答

多亏了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')。在

因此,我的问题是:

SELECT
    (strftime("%m", date_creation)) AS "month",
    (strftime("%Y", date_creation)) AS "year",
    COUNT(*) AS "total" FROM "app_request"
  GROUP BY
    (strftime("%m", date_creation)),
    (strftime("%Y", date_creation)),
    "app_request"."date_creation"

它打破了质疑。在

解决办法是:

^{pr2}$

实际上,我的解决方案从一开始就起作用了!在

以下是我的一个按小时分组的查询:

MyDateObject.objects.filter(**kwargs)\
                    .extra({ "hour": "date_part('hour', timestamp AT TIME ZONE '%s')" % (ctz.zone) })\
                    .values("hour")\
                    .annotate(Count("transaction", distinct=True))

我的和你的区别在于我使用的是extra函数。我想你应该做一些类似的事情,而不是你的第一个annotate像这样:

^{pr2}$

注意:我使用的是django1.9。在

编辑:我越看这个,也许我的计数中的distinct=True才真正起作用。在

相关问题 更多 >