pydantic / pydantic-settings

Settings management using pydantic
https://docs.pydantic.dev/latest/usage/pydantic_settings/
MIT License
508 stars 50 forks source link

Field with alias leads to ValidationError in v2.2.0 #239

Closed g3n35i5 closed 5 months ago

g3n35i5 commented 5 months ago
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings

class Item(BaseModel):
    item_type: str = Field(alias="itemType")

class ExampleConfig(BaseSettings):
    item: Item

if __name__ == "__main__":
    ExampleConfig(item=Item(itemType="EXAMPLE"))

results in

1 validation error for ExampleConfig
item.itemType
  Field required [type=missing, input_value={'item_type': 'EXAMPLE'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.6/v/missing
  File "/tmp/foo/pydantic_settings_issue.py", line 22, in <module>
    ExampleConfig(item=Item(itemType="EXAMPLE"))
pydantic_core._pydantic_core.ValidationError: 1 validation error for ExampleConfig
item.itemType
  Field required [type=missing, input_value={'item_type': 'EXAMPLE'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.6/v/missing

however just using it without the Field works:

class Item(BaseModel):
    item_type: str

This bug was introduced with v2.2.0, v2.1.0 works.

hramezani commented 5 months ago

Thanks @g3n35i5 for reporting this issue. Agree, it is a bug and has been introduced in https://github.com/pydantic/pydantic-settings/commit/2784a7013d0bccb5c76c2db78befe0c266baac55

I will create a fix for this bug soon

hramezani commented 5 months ago

@g3n35i5 Just created the PR https://github.com/pydantic/pydantic-settings/pull/240

It would be great if you can test and confirm the fix.

Thanks

g3n35i5 commented 5 months ago

@hramezani I can confirm that your bugfix works :blush: Thank you very much!

hramezani commented 5 months ago

pydantic-settings 2.2.1 has been released