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

Django将jsonb字段内datetime值强转查询时报DateTimeField无model属性错误

Django 3.2 下JSONB字段内部datetime值类型转换报错解决方案

错误根因

Django 3.2 版本未支持直接对JSONField嵌套键使用__取值后传入Cast做类型转换,直接使用该写法会导致框架无法识别字段归属,抛出'DateTimeField' object has no attribute 'model'错误。

解决方案

使用KeyTextTransform显式提取JSONB字段内部的datetime字符串值,再传入Cast做类型转换即可。

具体实现步骤

  1. 首先导入所需依赖
from django.db.models import DateTimeField, Cast
from django.db.models.fields.json import KeyTextTransform
  1. 调整annotate写法
Ticket.objects.annotate(
    datetime=Cast(
        KeyTextTransform('datetime', 'jsonb'),
        output_field=DateTimeField()
    )
)

补充说明

  • 你存储的2021-10-18 12:37:00.000Z格式属于标准UTC时间格式,Django的DateTimeField可直接正常解析,无需额外处理格式
  • 如果部分数据的jsonb字段不存在datetime键,可配合Coalesce设置默认值避免转换报错,示例:
from django.db.models import Coalesce, Value
from datetime import datetime

Ticket.objects.annotate(
    datetime=Coalesce(
        Cast(KeyTextTransform('datetime', 'jsonb'), output_field=DateTimeField()),
        Value(datetime(2000, 1, 1))
    )
)
  • 若升级到Django 4.0及以上版本,可直接使用你最初的写法Cast('jsonb__datetime', output_field=models.DateTimeField()),高版本已优化JSON嵌套字段的类型转换支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:42:02