Skip to content

Commit 982b142

Browse files
07pepa07pepa
authored andcommitted
fix incorrect type serialization when dumping to python
1 parent 54e0f2d commit 982b142

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

beanie/odm/fields.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def __get_pydantic_core_schema__(
152152
),
153153
json_schema=str_schema(),
154154
serialization=core_schema.plain_serializer_function_ser_schema(
155-
lambda instance: str(instance)
155+
lambda instance: str(instance), when_used="json"
156156
),
157157
)
158158

@@ -361,7 +361,7 @@ async def fetch_many(cls, links: List["Link"]):
361361
def serialize(value: Union["Link", BaseModel]):
362362
if isinstance(value, Link):
363363
return value.to_dict()
364-
return value.model_dump()
364+
return value.model_dump(mode="json")
365365

366366
@classmethod
367367
def build_validation(cls, handler, source_type):
@@ -415,7 +415,8 @@ def __get_pydantic_core_schema__(
415415
}
416416
),
417417
serialization=core_schema.plain_serializer_function_ser_schema( # type: ignore
418-
lambda instance: cls.serialize(instance) # type: ignore
418+
lambda instance: cls.serialize(instance),
419+
when_used="json", # type: ignore
419420
),
420421
)
421422
return core_schema.with_info_plain_validator_function(
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from pydantic import BaseModel, Field
2+
3+
from beanie import Link, PydanticObjectId
4+
from beanie.odm.utils.pydantic import IS_PYDANTIC_V2
5+
from tests.odm.models import DocumentTestModelWithSoftDelete
6+
7+
8+
class TestModel(BaseModel):
9+
my_id: PydanticObjectId = Field(default_factory=PydanticObjectId)
10+
fake_doc: Link[DocumentTestModelWithSoftDelete]
11+
12+
13+
def data_maker():
14+
return TestModel(
15+
my_id="5f4e3f3b7c0c9d001f7d4c8e",
16+
fake_doc=DocumentTestModelWithSoftDelete(
17+
test_int=1, test_str="test", id="5f4e3f3b7c0c9d001f7d4c8f"
18+
),
19+
)
20+
21+
22+
def test_id_types_preserved_when_dumping_to_python():
23+
if IS_PYDANTIC_V2:
24+
dumped = data_maker().model_dump(mode="python")
25+
assert isinstance(dumped["my_id"], PydanticObjectId)
26+
assert isinstance(dumped["fake_doc"]["id"], PydanticObjectId)
27+
28+
29+
def test_id_types_serialized_when_dumping_to_json():
30+
if IS_PYDANTIC_V2:
31+
dumped = data_maker().model_dump(mode="json")
32+
assert isinstance(dumped["my_id"], str)
33+
assert isinstance(dumped["fake_doc"]["id"], str)

0 commit comments

Comments
 (0)