【问题标题】:Django group by month and year doesnt workDjango 按月和年分组不起作用
【发布时间】: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}]

有什么想法吗?

【问题讨论】:

    标签: python django group-by


    【解决方案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:ordering = ['date_creation']

    因此,如果您不在查询中添加 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"
    

    它破坏了查询。

    解决办法是:

    print([v for v in
           Request.objects.annotate(month=ExtractMonth('date_creation'),
                                    year=ExtractYear('date_creation'),)
                          .order_by()
                          .values('month', 'year')
                          .annotate(total=Count('*'))
                          .values('month', 'year', 'total')
           ])
    

    实际上,我的解决方案从一开始就有效!

    【讨论】:

    • 我遇到了同样的问题。我的查询集是SomeClass.objects.annotate(month=ExtractMonth('created_at')).values('month').annotate(users=Count('id')) 所以通过查看你的答案,我编辑了我的查询集SomeClass.objects.annotate(month=ExtractMonth('created_at')).values('month').annotate(users=Count('id')).order_by('created_at__month') 对我来说,最后一个注释工作后的 order_by('created_at__month') 。谢谢
    【解决方案2】:

    这是我的一个查询按小时分组的样子:

    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

    Request.objects.extra({ "month": ExtractMonth('date_creation'),
                            "year": ExtractYear('date_creation') })
                   .values('month', 'year')
                   .annotate(total=Count('month'))
                   .values('month', 'year', 'total')
    

    注意:我使用的是 Django 1.9。

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

    【讨论】:

    • 如果我尝试您的解决方案,我会收到错误消息:django.db.utils.OperationalError: no such function: F。尝试的查询是SELECT (ExtractMonth(F(date_creation))) AS "month", (ExtractYear(F(date_creation))) AS "year", COUNT(*) AS "total" FROM "app_request" GROUP BY (ExtractMonth(F(date_creation))), (ExtractYear(F(date_creation))), "app_request"."date_v_debut" ORDER BY "app_request"."date_v_debut" ASC
    • 我已经更新了我的问题。我的最新查询与您的非常接近。
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2011-07-21
    • 2021-10-16
    相关资源
    最近更新 更多