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
80%Fix Rate
88%Confidence
0Evidence
2024-05-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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() -
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:
-
80% fail
model_dump() returns Python objects, so json.dumps fails with the same underlying non-serializable type error.
-
60% fail
Changes validation semantics and loses type information for all consumers, not just serialization.