You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Tortoise ORM实现date_trunc分组查询时遇KeyError 'hour'求助

解决Tortoise ORM中DateTrunc导致的KeyError 'hour'问题

错误原因

你调用DateTrunc时直接传入了"hour"字符串,Tortoise会将其当作模型字段名去查找,但你的ABC模型中并没有hour字段,因此触发KeyError。同时,CustomFunction的参数列表定义也需要适配常量+字段的传入方式。

修复步骤

1. 修正DateTrunc函数定义

调整CustomFunction的参数列表,明确参数用途:

from tortoise.functions import Function, CustomFunction

class DateTrunc(Function):
    # 定义date_trunc的参数:第一个是时间间隔(常量),第二个是时间字段
    database_func = CustomFunction("date_trunc", ["interval_part", "datetime_field"])

2. 使用Value包装常量参数

调用DateTrunc时,用Value类包装"hour",告诉Tortoise这是一个字符串常量而非字段名:

from tortoise.expressions import Value, Count

# 修正后的查询代码
ABC.filter(user_id=user_id, active=True) \
    .annotate(
        count=Count("id"), 
        group_name=DateTrunc(Value("hour"), "created")
    ) \
    .group_by('group_name') \
    .order_by('-group_name')  # 对应原SQL的DESC排序
    .values_list('group_name', 'count') \
    .sql()

额外说明

  • 原SQL中是ORDER BY group_name DESC,Tortoise中用'-group_name'表示降序排序。
  • Value类用于将字面量值传入SQL函数,避免被解析为模型字段。

内容的提问来源于stack exchange,提问作者Bhawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:25:40