【问题标题】:Extra GROUP BY clause in django queryDjango 查询中的额外 GROUP BY 子句
【发布时间】:2015-07-28 23:43:26
【问题描述】:

我已经编写了这个 Django ORM 查询:

queryset = Test.objects.all() \
    .annotate_test_date() \ # similar to extract hour 
    .annotate_test_time() \ # similar to extract hour 
    .annotate(hour=Extract(F('created_on'), function='hour')) \
    .annotate(count=Count('id')) \
    .order_by() \
    .values('hour', 'count')

形成的查询结果是:

SELECT extract (hour from ("users_test"."created_on")) AS "hour",
COUNT("users_test"."id") AS "count" 
FROM "users_test" 
GROUP BY "users_test"."id", "users_test"."author_id", "users_test"."created_on", "users_test"."modified_on", "users_test"."access_point_id", "users_test"."user_id", "users_test"."invite_id", "users_test"."building_id", "users_test"."company_id", date("users_test"."created_on"), "time"("users_test"."created_on"), extract (hour from ("users_test"."created_on"))

但所需的查询是:

SELECT extract (hour from ("users_test"."created_on")) AS "hour",
COUNT("users_test"."id") AS "count" 
FROM "users_test" 
GROUP BY extract (hour from ("users_test"."created_on"))

我认为这是由于我的查询中有额外的注释字段,但这些字段是过滤所必需的。

感谢任何帮助。

提前致谢

【问题讨论】:

    标签: django postgresql django-queryset django-orm django-1.8


    【解决方案1】:

    按此顺序尝试:

    queryset = Test.objects.all() \
        .annotate(hour=Extract(F('created_on'), function='hour')) \
        .annotate(count=Count('id')) \
        .values('hour', 'count')
        .order_by()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2013-08-12
    • 1970-01-01
    • 2016-05-09
    • 2021-04-05
    相关资源
    最近更新 更多