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
4 changes: 4 additions & 0 deletions sqlmodel/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ def sqlmodel_validate(
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
update: dict[str, Any] | None = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
Expand All @@ -303,6 +305,8 @@ def sqlmodel_validate(
strict=strict,
from_attributes=from_attributes,
context=context,
by_alias=by_alias,
by_name=by_name,
self_instance=new_obj,
)
# Capture fields set to restore it later
Expand Down
4 changes: 4 additions & 0 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,8 @@ def model_validate( # ty: ignore[invalid-method-override]
strict: bool | None = None,
from_attributes: bool | None = None,
context: builtins.dict[str, Any] | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
update: builtins.dict[str, Any] | None = None,
) -> _TSQLModel:
return sqlmodel_validate(
Expand All @@ -884,6 +886,8 @@ def model_validate( # ty: ignore[invalid-method-override]
strict=strict,
from_attributes=from_attributes,
context=context,
by_alias=by_alias,
by_name=by_name,
update=update,
)

Expand Down
23 changes: 23 additions & 0 deletions tests/test_aliases.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,26 @@ class M(SQLModel):
assert m.f == "ok"
data = m.model_dump(by_alias=True)
assert "custom" in data and "gen_f" not in data


@pytest.mark.parametrize("model", [PydanticUser, SQLModelUser])
def test_model_validate_by_name(
model: type[PydanticUser] | type[SQLModelUser],
):
# By default, a field with an alias can't be populated by its name
with pytest.raises(ValidationError):
model.model_validate({"full_name": "Greg"})
# With by_name=True, the field name is accepted
user = model.model_validate({"full_name": "Greg"}, by_name=True)
assert user.full_name == "Greg"


@pytest.mark.parametrize("model", [PydanticUser, SQLModelUser])
def test_model_validate_by_alias_and_by_name(
model: type[PydanticUser] | type[SQLModelUser],
):
# With both enabled, either the alias or the field name is accepted
by_alias = model.model_validate({"fullName": "Helen"}, by_alias=True, by_name=True)
assert by_alias.full_name == "Helen"
by_name = model.model_validate({"full_name": "Helen"}, by_alias=True, by_name=True)
assert by_name.full_name == "Helen"
Loading