django查询中的额外GROUP BY子句

时间:2015-05-17 12:16:43

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

我写过这个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"))

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

感谢任何帮助。

先谢谢

1 个答案:

答案 0 :(得分:0)

尝试按此顺序:

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