-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Fix validation_alias behavior with model_construct for AliasChoices and AliasPath
#9223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Deploying pydantic-docs with
|
| Latest commit: |
c1d585f
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://9d295dfb.pydantic-docs2.pages.dev |
| Branch Preview URL: | https://full-alias-fix.pydantic-docs2.pages.dev |
CodSpeed Performance ReportMerging #9223 will not alter performanceComparing Summary
|
|
Please review |
|
One potential issue with this approach — the following code errors for normal validation: from pydantic import BaseModel, AliasPath, Field
class MyModel(BaseModel):
x: str = Field(alias=AliasPath('y', 1))
print(MyModel(y=['abc', 'def']))
print(MyModel(y='abc'))
"""
y.1
Field required [type=missing, input_value={'y': 'abc'}, input_type=dict]
"""and if you add a default, you get the default: from pydantic import BaseModel, AliasPath, Field
class MyModel(BaseModel):
x: str = Field(default='xyz', alias=AliasPath('y', 1))
print(MyModel(y=['abc', 'def']))
#> x='def'
print(MyModel(y='abc'))
#> x='xyz'However, with your current implementation, if you use from pydantic import BaseModel, AliasPath, Field
class MyModel(BaseModel):
x: str = Field(default='xyz', alias=AliasPath('y', 1))
print(MyModel.model_construct(y=['abc', 'def']))
#> x='def' (as expected)
print(MyModel.model_construct(y='abc'))
#> x='b' (not expected)Not sure if this is a blocking-level problem, or if it's worth the overhead it would add to prevent this misbehavior. |
|
Just added an from pydantic import BaseModel, AliasPath, Field
class MyModel(BaseModel):
x: str = Field(default='xyz', validation_alias=AliasPath('y', 1))
print(MyModel.model_construct(y=['abc', 'def']))
#> x='def' (as expected)
print(MyModel.model_construct(y='abc'))
#> x='xyz' (as expected) |
validation_alias behavior with model_construct for AliasChoices and AliasPath
Fix #9216
Fix #9220
Initially introduced in #9144 because we forgot to account for
AliasPathandAliasChoicesvalidation aliases!Selected Reviewer: @adriangb