close
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,7 @@ def model_dump(
warnings: bool | Literal["none", "warn", "error"] = True,
fallback: Callable[[Any], Any] | None = None, # v2.11
serialize_as_any: bool = False, # v2.7
polymorphic_serialization: bool | None = None, # v2.13
) -> builtins.dict[str, Any]:
if PYDANTIC_MINOR_VERSION < (2, 11):
by_alias = by_alias or False
Expand All @@ -913,6 +914,8 @@ def model_dump(
extra_kwargs["fallback"] = fallback
if PYDANTIC_MINOR_VERSION >= (2, 12):
extra_kwargs["exclude_computed_fields"] = exclude_computed_fields
if PYDANTIC_MINOR_VERSION >= (2, 13):
extra_kwargs["polymorphic_serialization"] = polymorphic_serialization
return super().model_dump(
mode=mode,
include=include,
Expand Down
47 changes: 47 additions & 0 deletions tests/test_pydantic/test_model_dump.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from typing import Any

import pytest
from sqlmodel import SQLModel
from sqlmodel._compat import PYDANTIC_MINOR_VERSION


@pytest.mark.parametrize(
("polymorphic_serialization", "expected_result"),
[
(None, {"user": {"name": "pydantic"}}),
(False, {"user": {"name": "pydantic"}}),
pytest.param(
True,
{"user": {"name": "pydantic", "password": "password"}},
marks=pytest.mark.skipif(
PYDANTIC_MINOR_VERSION < (2, 13),
reason="polymorphic_serialization is only available in Pydantic v2.13+",
),
),
],
)
def test_polymorphic_serialization(
polymorphic_serialization: bool | None, expected_result: dict[str, Any]
):

class User(SQLModel):
name: str

class UserLogin(User):
password: str

class OuterModel(SQLModel):
user: User

outer_model = OuterModel(
user=UserLogin(name="pydantic", password="password"),
)

assert (
outer_model.model_dump(polymorphic_serialization=polymorphic_serialization)
== expected_result
)

assert outer_model.model_dump(polymorphic_serialization=False) == {
"user": {"name": "pydantic"}
}
Loading
Loading