Skip to content

Commit 3652fbd

Browse files
authored
Fix InitSource bug in case of nested model using alias (#240)
1 parent 859805a commit 3652fbd

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

pydantic_settings/sources.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str,
165165
return None, '', False
166166

167167
def __call__(self) -> dict[str, Any]:
168-
return TypeAdapter(Dict[str, Any]).dump_python(self.init_kwargs)
168+
return TypeAdapter(Dict[str, Any]).dump_python(self.init_kwargs, by_alias=True)
169169

170170
def __repr__(self) -> str:
171171
return f'InitSettingsSource(init_kwargs={self.init_kwargs!r})'

tests/test_settings.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2367,3 +2367,14 @@ class Settings(BaseSettings):
23672367

23682368
s = Settings()
23692369
assert s.model_dump() == {'foo': '1', 'extra_var': 'extra_value'}
2370+
2371+
2372+
def test_nested_field_with_alias_init_source():
2373+
class NestedSettings(BaseModel):
2374+
foo: str = Field(alias='fooAlias')
2375+
2376+
class Settings(BaseSettings):
2377+
nested_foo: NestedSettings
2378+
2379+
s = Settings(nested_foo=NestedSettings(fooAlias='EXAMPLE'))
2380+
assert s.model_dump() == {'nested_foo': {'foo': 'EXAMPLE'}}

0 commit comments

Comments
 (0)