python type_error ai_generated true

pydantic_core._pydantic_core.PydanticSerializationError: 无法序列化未知类型: <class 'datetime.date'>

pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'datetime.date'>

ID: python/pydantic-model-dump-json-not-serializable

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-30首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

model_dump_json 或 model_dump(mode='json') 遇到没有注册序列化器的类型,通常是 Any 字段中的自定义类或第三方对象。

English

model_dump_json or model_dump(mode='json') encountered a type with no registered serializer, often a custom class or a third-party object stored in an Any field.

generic

解决方案

  1. 93% 成功率
    from datetime import date
    from pydantic import BaseModel, field_serializer
    
    class Model(BaseModel):
        d: date
    
        @field_serializer('d')
        def ser_date(self, v: date, _info):
            return v.isoformat()
  2. 90% 成功率
    from typing import Annotated
    from pydantic import PlainSerializer
    
    IsoDate = Annotated[date, PlainSerializer(lambda v: v.isoformat(), return_type=str)]

无效尝试

常见但无效的做法:

  1. 80% 失败

    model_dump() returns Python objects, so json.dumps fails with the same underlying non-serializable type error.

  2. 60% 失败

    Changes validation semantics and loses type information for all consumers, not just serialization.