Skip to content

Commit

Permalink
Use __pydantic_serializer__ for serializing Any fields (pydantic#5578)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed May 5, 2023
1 parent 8847c76 commit 8c60d1d
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Any, Optional

import pytest
from pydantic_core import PydanticSerializationError, core_schema
from pydantic_core import PydanticSerializationError, core_schema, to_jsonable_python
from typing_extensions import Annotated

from pydantic import (
Expand Down Expand Up @@ -768,3 +768,20 @@ class Model(BaseModel):
not_ser_x = field_serializer('y')(ser)

assert Model(x=1_000, y=2_000).model_dump() == {'x': '1,000', 'y': '2,000'}


def test_serialize_any_model():
class Model(BaseModel):
m: str

@field_serializer('m')
def ser_m(self, v: str, _info: SerializationInfo) -> str:
return f'custom:{v}'

class AnyModel(BaseModel):
x: Any

m = Model(m='test')
assert m.model_dump() == {'m': 'custom:test'}
assert to_jsonable_python(AnyModel(x=m)) == {'x': {'m': 'custom:test'}}
assert AnyModel(x=m).model_dump() == {'x': {'m': 'custom:test'}}

0 comments on commit 8c60d1d

Please sign in to comment.