Allow AliasChoices and AliasPath for validation_alias in Field

This commit is contained in:
Yurii Motov
2026-01-28 21:50:45 +01:00
parent 5611bda2e5
commit b15644e819
3 changed files with 46 additions and 7 deletions

View File

@@ -1,9 +1,11 @@
from typing import Union
from typing import Optional, Union
import pytest
from pydantic import AliasChoices as PAliasChoices
from pydantic import AliasPath as PAliasPath
from pydantic import BaseModel, ValidationError
from pydantic import Field as PField
from sqlmodel import Field, SQLModel
from sqlmodel import AliasChoices, AliasPath, Field, SQLModel
"""
Alias tests for SQLModel and Pydantic compatibility
@@ -99,10 +101,22 @@ def test_json_by_alias(
class PydanticUserV2(BaseModel):
first_name: str = PField(validation_alias="firstName", serialization_alias="f_name")
second_name: Optional[str] = PField(
default=None, validation_alias=PAliasChoices("secondName", "surname")
)
nickname: Optional[str] = PField(
default=None, validation_alias=PAliasPath("names", 2)
)
class SQLModelUserV2(SQLModel):
first_name: str = Field(validation_alias="firstName", serialization_alias="f_name")
second_name: Optional[str] = Field(
default=None, validation_alias=AliasChoices("secondName", "surname")
)
nickname: Optional[str] = Field(
default=None, validation_alias=AliasPath("names", 2)
)
@pytest.mark.parametrize("model", [PydanticUserV2, SQLModelUserV2])
@@ -113,6 +127,27 @@ def test_create_with_validation_alias(
assert user.first_name == "John"
@pytest.mark.parametrize("model", [PydanticUserV2, SQLModelUserV2])
def test_create_with_validation_alias_alias_choices(
model: Union[type[PydanticUserV2], type[SQLModelUserV2]],
):
user = model.model_validate({"firstName": "John", "secondName": "Doe"})
assert user.second_name == "Doe"
user2 = model.model_validate({"firstName": "John", "surname": "Doe"})
assert user2.second_name == "Doe"
@pytest.mark.parametrize("model", [PydanticUserV2, SQLModelUserV2])
def test_create_with_validation_alias_alias_path(
model: Union[type[PydanticUserV2], type[SQLModelUserV2]],
):
user = model.model_validate(
{"firstName": "John", "names": ["John", "Doe", "Johnny"]}
)
assert user.nickname == "Johnny"
@pytest.mark.parametrize("model", [PydanticUserV2, SQLModelUserV2])
def test_serialize_with_serialization_alias(
model: Union[type[PydanticUserV2], type[SQLModelUserV2]],