python type_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

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

中文

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

Workarounds

  1. 93% success
    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% success
    from typing import Annotated
    from pydantic import PlainSerializer
    
    IsoDate = Annotated[date, PlainSerializer(lambda v: v.isoformat(), return_type=str)]

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 60% fail

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