我写了这个 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"))
我相信这是由于我的查询中有额外的注释字段,但这些字段是过滤所必需的。
任何帮助表示赞赏。
提前致谢