【问题标题】:Hourly grouping of rows using Django使用 Django 每小时对行进行分组
【发布时间】:2015-07-28 00:28:20
【问题描述】:

我一直在尝试使用DateTimeField 将表格结果分组为每小时格式。

SQL:

SELECT strftime('%H', created_on), count(*)
FROM users_test
GROUP BY strftime('%H', created_on);

这个查询工作正常,但相应的 Django 查询却不行。

我尝试过的 Django 查询:

Test.objects.extra({'hour': 'strftime("%%H", created_on)'}).values('hour').annotate(count=Count('id'))
# SELECT (strftime("%H", created_on)) AS "hour", COUNT("users_test"."id") AS "count" FROM "users_test" GROUP BY (strftime("%H", created_on)), "users_test"."created_on" ORDER BY "users_test"."created_on" DESC

它通过“users_test”添加了额外的组。“created_on”,我猜这给出了不正确的结果。

如果有人能向我解释这一点并提供解决方案,那就太好了。

环境:

  • Python 3
  • Django 1.8.1

提前致谢

参考(可能重复)(但没有帮助):

【问题讨论】:

    标签: django postgresql django-1.8


    【解决方案1】:

    要修复它,请将order_by() 附加到查询链。这将覆盖模型 Meta 默认排序。像这样:

    Test
    .objects
    .extra({'hour': 'strftime("%%H", created_on)'})
    .order_by()                                        #<------ here
    .values('hour')
    .annotate(count=Count('id'))
    

    在我的环境中(Postgres 也是):

    >>> print ( Material
             .objects
             .extra({'hour': 'strftime("%%H", data_creacio)'})
             .order_by()
             .values('hour')
             .annotate(count=Count('id'))
             .query )
    
      SELECT (strftime("%H", data_creacio)) AS "hour", 
             COUNT("material_material"."id") AS "count" 
        FROM "material_material" 
    GROUP BY (strftime("%H", data_creacio))
    

    order_by django docs了解更多信息:

    如果您不希望对查询应用任何排序,甚至是默认排序,请不带参数调用 order_by()。

    旁注: 使用extra() 可能会在您的代码中引入SQL injection vulnerability。谨慎使用它并转义用户可以引入的任何参数。 Compare with docs:

    警告

    每次使用 extra() 时都应该非常小心。每次你 使用它,您应该转义用户可以控制的任何参数 使用参数来防止 SQL 注入攻击。 请阅读更多关于SQL injection protection的信息。

    【讨论】:

    • 这个答案已经很老了,但是你冒着引入 SQL 注入的风险。在此特定示例中可能并非如此,但请注意它可能很棘手。 You should be very careful whenever you use extra(). Every time you use it, you should escape any parameters that the user can control by using params in order to protect against SQL injection attacks .docs.djangoproject.com/en/1.11/ref/models/querysets/…
    • 嗨@gonczor,好镜头。你有> 2k。你好心编辑答案吗?
    • 完成。很高兴我能帮忙:)
    • 感谢改进 SO。
    猜你喜欢
    • 2019-08-19
    • 2020-05-15
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2021-07-25
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多