gpt4 book ai didi

django - Django 查询中的额外 GROUP BY 子句

转载 作者:行者123 更新时间:2023-11-29 12:26:53 25 4
gpt4 key购买 nike

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

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

感谢任何帮助。

提前致谢

最佳答案

按以下顺序尝试:

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

关于django - Django 查询中的额外 GROUP BY 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com