CodeBlanks Logo Icon CodeBlanks

Config

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: str

str_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: str

These 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

main.py
# 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 name

Sample solution

main.py
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

Question
from pydantic import BaseModel, ConfigDict

class User(BaseModel):
    ____ = ConfigDict(str_min_length=1)
    name: str
Answer
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

All lessons in Advanced