diff --git a/sqlmodel/_compat.py b/sqlmodel/_compat.py index a220b193f1..0f9f0e306e 100644 --- a/sqlmodel/_compat.py +++ b/sqlmodel/_compat.py @@ -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): @@ -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 diff --git a/sqlmodel/main.py b/sqlmodel/main.py index 9a1a676775..bbc17fa6d1 100644 --- a/sqlmodel/main.py +++ b/sqlmodel/main.py @@ -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( @@ -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, ) diff --git a/tests/test_aliases.py b/tests/test_aliases.py index f0ebf747b4..c233834759 100644 --- a/tests/test_aliases.py +++ b/tests/test_aliases.py @@ -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"