1- from typing import Union
1+ from typing import Optional , Union
22
33import pytest
4+ from pydantic import AliasChoices as PAliasChoices
5+ from pydantic import AliasPath as PAliasPath
46from pydantic import BaseModel , ValidationError
57from pydantic import Field as PField
6- from sqlmodel import Field , SQLModel
8+ from sqlmodel import AliasChoices , AliasPath , Field , SQLModel
79
810"""
911Alias tests for SQLModel and Pydantic compatibility
@@ -99,10 +101,22 @@ def test_json_by_alias(
99101
100102class PydanticUserV2 (BaseModel ):
101103 first_name : str = PField (validation_alias = "firstName" , serialization_alias = "f_name" )
104+ second_name : Optional [str ] = PField (
105+ default = None , validation_alias = PAliasChoices ("secondName" , "surname" )
106+ )
107+ nickname : Optional [str ] = PField (
108+ default = None , validation_alias = PAliasPath ("names" , 2 )
109+ )
102110
103111
104112class SQLModelUserV2 (SQLModel ):
105113 first_name : str = Field (validation_alias = "firstName" , serialization_alias = "f_name" )
114+ second_name : Optional [str ] = Field (
115+ default = None , validation_alias = AliasChoices ("secondName" , "surname" )
116+ )
117+ nickname : Optional [str ] = Field (
118+ default = None , validation_alias = AliasPath ("names" , 2 )
119+ )
106120
107121
108122@pytest .mark .parametrize ("model" , [PydanticUserV2 , SQLModelUserV2 ])
@@ -113,6 +127,27 @@ def test_create_with_validation_alias(
113127 assert user .first_name == "John"
114128
115129
130+ @pytest .mark .parametrize ("model" , [PydanticUserV2 , SQLModelUserV2 ])
131+ def test_create_with_validation_alias_alias_choices (
132+ model : Union [type [PydanticUserV2 ], type [SQLModelUserV2 ]],
133+ ):
134+ user = model .model_validate ({"firstName" : "John" , "secondName" : "Doe" })
135+ assert user .second_name == "Doe"
136+
137+ user2 = model .model_validate ({"firstName" : "John" , "surname" : "Doe" })
138+ assert user2 .second_name == "Doe"
139+
140+
141+ @pytest .mark .parametrize ("model" , [PydanticUserV2 , SQLModelUserV2 ])
142+ def test_create_with_validation_alias_alias_path (
143+ model : Union [type [PydanticUserV2 ], type [SQLModelUserV2 ]],
144+ ):
145+ user = model .model_validate (
146+ {"firstName" : "John" , "names" : ["John" , "Doe" , "Johnny" ]}
147+ )
148+ assert user .nickname == "Johnny"
149+
150+
116151@pytest .mark .parametrize ("model" , [PydanticUserV2 , SQLModelUserV2 ])
117152def test_serialize_with_serialization_alias (
118153 model : Union [type [PydanticUserV2 ], type [SQLModelUserV2 ]],
0 commit comments