Skip to content

Commit 6c60b87

Browse files
committed
Fix #166 - Add docs for validating default values
1 parent 3205f81 commit 6c60b87

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

docs/index.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,42 @@ print(Settings().model_dump())
104104

105105
Check the [Environment variable names documentation](#environment-variable-names) for more information.
106106

107+
## Validation of default values
108+
109+
Unlike pydantic `BaseModel`, default values of `BaseSettings` fields are validated by default.
110+
You can disable this behaviour by setting `validate_default=False` either in `model_config`
111+
or on field-by-field basis:
112+
113+
```py
114+
import datetime as dt
115+
116+
from pydantic import Field
117+
from pydantic.functional_validators import BeforeValidator
118+
from typing_extensions import Annotated
119+
120+
from pydantic_settings import BaseSettings, SettingsConfigDict
121+
122+
123+
def str_to_date(v: str) -> dt.date:
124+
return dt.date.fromisoformat(v)
125+
126+
127+
class GlobalSettings(BaseSettings):
128+
model_config = SettingsConfigDict(validate_default=False)
129+
130+
# default won't be validated
131+
date: Annotated[dt.date, BeforeValidator(str_to_date)] = dt.date(2000, 1, 1)
132+
133+
134+
class LocalSettings(BaseSettings):
135+
# default won't be validated
136+
date: Annotated[dt.date, BeforeValidator(str_to_date)] = Field(
137+
default=dt.date(2000, 1, 1), validate_default=False
138+
)
139+
```
140+
141+
Check the [Validation of default values](validators.md#validation-of-default-values) for more information.
142+
107143
## Environment variable names
108144

109145
By default, the environment variable name is the same as the field name.

0 commit comments

Comments
 (0)