Skip to content

Commit

Permalink
fix incorrect type serialization when dumping to python
Browse files Browse the repository at this point in the history
  • Loading branch information
07pepa authored and 07pepa committed Aug 14, 2024
1 parent 54e0f2d commit 982b142
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
7 changes: 4 additions & 3 deletions beanie/odm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def __get_pydantic_core_schema__(
),
json_schema=str_schema(),
serialization=core_schema.plain_serializer_function_ser_schema(
lambda instance: str(instance)
lambda instance: str(instance), when_used="json"
),
)

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

@classmethod
def build_validation(cls, handler, source_type):
Expand Down Expand Up @@ -415,7 +415,8 @@ def __get_pydantic_core_schema__(
}
),
serialization=core_schema.plain_serializer_function_ser_schema( # type: ignore
lambda instance: cls.serialize(instance) # type: ignore
lambda instance: cls.serialize(instance),
when_used="json", # type: ignore
),
)
return core_schema.with_info_plain_validator_function(
Expand Down
33 changes: 33 additions & 0 deletions tests/odm/test_beanie_object_dumping.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from pydantic import BaseModel, Field

from beanie import Link, PydanticObjectId
from beanie.odm.utils.pydantic import IS_PYDANTIC_V2
from tests.odm.models import DocumentTestModelWithSoftDelete


class TestModel(BaseModel):
my_id: PydanticObjectId = Field(default_factory=PydanticObjectId)
fake_doc: Link[DocumentTestModelWithSoftDelete]


def data_maker():
return TestModel(
my_id="5f4e3f3b7c0c9d001f7d4c8e",
fake_doc=DocumentTestModelWithSoftDelete(
test_int=1, test_str="test", id="5f4e3f3b7c0c9d001f7d4c8f"
),
)


def test_id_types_preserved_when_dumping_to_python():
if IS_PYDANTIC_V2:
dumped = data_maker().model_dump(mode="python")
assert isinstance(dumped["my_id"], PydanticObjectId)
assert isinstance(dumped["fake_doc"]["id"], PydanticObjectId)


def test_id_types_serialized_when_dumping_to_json():
if IS_PYDANTIC_V2:
dumped = data_maker().model_dump(mode="json")
assert isinstance(dumped["my_id"], str)
assert isinstance(dumped["fake_doc"]["id"], str)

0 comments on commit 982b142

Please sign in to comment.