Config
- Python course
- Advanced
- Lesson 58/83
- 5 min
Learn model config with model_config.
Config
In Pydantic v2, model settings are made with model_config. It uses ConfigDict instead of the old class Config. Settings control strictness, extra fields, ORM mode and other behavior.
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(str_min_length=1)
name: strstr_min_length=1 applies a minimum length of 1 to all string fields. With extra="forbid" you reject unknown fields.
Common settings
extra="forbid" rejects unknown fields; extra="ignore" silently drops them. str_min_length and str_max_length apply to all string fields.
class User(BaseModel):
model_config = ConfigDict(
extra="forbid",
str_min_length=1,
)
name: strThese settings are useful for strict behavior such as rejecting unexpected fields in APIs. ORM mode is also enabled here, so you can work with database models easily.
Practice User model with ConfigDict
Start with from pydantic import BaseModel, ConfigDict. Define class User(BaseModel):. Add model_config = ConfigDict(str_min_length=2). Add field name: str. Create an instance with u = User(name="Ayşe"). Print the name with print(u.name).
Starter code
# bring in BaseModel and ConfigDict from pydantic
# define User class (derive from BaseModel)
# add a min length of 2 for all string fields via model_config
# define the name field
# create a User instance and print the nameSample solution
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(str_min_length=2)
name: str
u = User(name="Ayşe")
print(u.name)Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which attribute holds model settings in Pydantic v2?
- settings
- class Config
- __config__
- model_config Correct answer
Explanation: The model_config attribute holds settings in v2.
2 Complete the model_config assignment
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
____ = ConfigDict(str_min_length=1)
name: str
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(str_min_length=1)
name: str
Explanation: model_config = ConfigDict(...) sets the settings.
3 Match the Config concepts
| Term | Meaning |
|---|---|
model_config |
Holds settings |
ConfigDict |
Creates a settings dict |
extra='forbid' |
Rejects unknown |
str_min_length |
String min length |