PlainSerializer not working for extra field
Author: cute149qCreated Jun 19, 2024Updated Sep 27, 2026
Labelsbug V2
Initial Checks
- I confirm that I'm using Pydantic V2
Description
I tried to use PlainSerializer for the transformation for the extra fields. However, it is not working when there are several types in the extra field.
e.g. If there is datetime and string in the extra field, the PlainSerializer will not be excuted.
Example Code
from datetime import datetime
from typing import Annotated, Dict
from pydantic import BaseModel, ConfigDict, PlainSerializer, Field
def trans_datetime(dt: datetime) -> str:
# Test that the `add_utc_timezone` function works as expected
return dt.isoformat()
TransDatetime = Annotated[
datetime,
PlainSerializer(trans_datetime, when_used='json')
]
class TimeInfo(BaseModel):
start_time: TransDatetime
model_config = ConfigDict(frozen=True, json_encoders={datetime: trans_datetime}, extra="allow")
__pydantic_extra__: Dict[str, TransDatetime | Any] = Field(init=False)
InstanceTime = TimeInfo(start_time=datetime.now(), end_time=datetime.now(), name="name")
print(InstanceTime.model_dump_json())
#> Expectation: {"start_time":"2024-06-18T13:00:52.991797","end_time":"2024-06-18T13:00:52.991804", "name": "asdfasdf"}Python, Pydantic & OS Version
pydantic version: 2.7.4
pydantic-core version: 2.18.4
pydantic-core build: profile=release pgo=true
python version: 3.11.4 (main, Jun 20 2023, 17:37:48) [Clang 14.0.0 (clang-1400.0.29.202)]
platform: macOS-14.5-arm64-i386-64bit
related packages: mypy-1.10.0 typing_extensions-4.12.2Source: pydantic/pydantic