Skip to content

Commit

Permalink
Fix a bug when using BaseSettings with RootModel
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Jul 10, 2023
1 parent 1da9fab commit 1496aff
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ class Sub(BaseModel):
class Settings(BaseSettings):
nested: Sub
model_config = ConfigDict(env_nested_delimiter='__')
model_config = SettingsConfigDict(env_nested_delimiter='__')
```
Then:
Expand Down Expand Up @@ -241,7 +241,11 @@ def __call__(self) -> dict[str, Any]:
) from e

if field_value is not None:
if not self.case_sensitive and lenient_issubclass(field.annotation, BaseModel):
if (
not self.case_sensitive
and lenient_issubclass(field.annotation, BaseModel)
and isinstance(field_value, dict)
):
data[field_key] = self._replace_field_names_case_insensitively(field, field_value)
else:
data[field_key] = field_value
Expand Down
16 changes: 16 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Field,
HttpUrl,
Json,
RootModel,
SecretStr,
ValidationError,
)
Expand Down Expand Up @@ -1773,3 +1774,18 @@ class Settings(BaseSettings, env_prefix='foobar_', title='Test Settings Model'):
env.set('foobar_apple', 'has_prefix')
s = Settings()
assert s.apple == 'has_prefix'


def test_root_model_as_field(env):
class Foo(BaseModel):
x: int
y: Dict[str, int]

FooRoot = RootModel[List[Foo]]

class Settings(BaseSettings):
z: FooRoot

env.set('z', '[{"x": 1, "y": {"foo": 1}}, {"x": 2, "y": {"foo": 2}}]')
s = Settings()
assert s.model_dump() == {'z': [{'x': 1, 'y': {'foo': 1}}, {'x': 2, 'y': {'foo': 2}}]}

0 comments on commit 1496aff

Please sign in to comment.