Model Config

Behaviour of pydantic can be controlled via the Config class on a model.


the title for the generated JSON Schema
whether to strip leading and trailing whitespace for str & byte types (default: False)
the min length for str & byte types (default: 0)
the max length for str & byte types (default: 2 ** 16)
whether to validate field defaults (default: False)
whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore', 'allow', or 'forbid', or values of the Extra enum (default: Extra.ignore)
whether or not models are faux-immutable, i.e. whether __setattr__ is allowed (default: True)
whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False)
a dict containing schema information for each field; this is equivalent to using the schema class (default: None)
whether to perform validation on assignment to attributes (default: False)
whether an aliased field may be populated by its name as given by the model attribute, as well as the alias (default: False)


The name of this configuration setting was changed in v1.0 from allow_population_by_alias to allow_population_by_field_name.

a dict used to override the default error message templates. Pass in a dictionary with keys matching the error messages you want to override (default: {})
whether to allow arbitrary user types for fields (they are validated simply by checking if the value is an instance of the type). If False, RuntimeError will be raised on model declaration (default: False)
whether to allow usage of ORM mode
a custom class (which should inherit from GetterDict) to use when decomposing ORM classes for validation, for use with orm_mode
a callable that takes a field name and returns an alias for it
a tuple of types (e.g. descriptors) for a model's default values that should not be changed during model creation and will not be included in the model schemas. Note: this means that attributes on the model with defaults of this type, not annotations of this type, will be left alone.
a dict used to extend/update the generated JSON Schema, or a callable to post-process it; see Schema customization
a custom function for decoding JSON; see custom JSON (de)serialisation
a custom function for encoding JSON; see custom JSON (de)serialisation
a dict used to customise the way types are encoded to JSON; see JSON Serialisation
from pydantic import BaseModel, ValidationError

class Model(BaseModel):
    v: str

    class Config:
        max_anystr_length = 10
        error_msg_templates = {
            'value_error.any_str.max_length': 'max_length:{limit_value}',

    Model(v='x' * 20)
except ValidationError as e:
1 validation error for Model
  max_length:10 (type=value_error.any_str.max_length; limit_value=10)

(This script is complete, it should run "as is")

Similarly, if using the @dataclass decorator:

from datetime import datetime

from pydantic import ValidationError
from pydantic.dataclasses import dataclass

class MyConfig:
    max_anystr_length = 10
    validate_assignment = True
    error_msg_templates = {
        'value_error.any_str.max_length': 'max_length:{limit_value}',

class User:
    id: int
    name: str = 'John Doe'
    signup_ts: datetime = None

user = User(id='42', signup_ts='2032-06-21T12:00')
try: = 'x' * 20
except ValidationError as e:
1 validation error for User
  max_length:10 (type=value_error.any_str.max_length; limit_value=10)

(This script is complete, it should run "as is")

Alias Generator🔗

If data source field names do not match your code style (e. g. CamelCase fields), you can automatically generate aliases using alias_generator:

from pydantic import BaseModel

def to_camel(string: str) -> str:
    return ''.join(word.capitalize() for word in string.split('_'))

class Voice(BaseModel):
    name: str
    language_code: str

    class Config:
        alias_generator = to_camel

voice = Voice(Name='Filiz', LanguageCode='tr-TR')
#> tr-TR
#> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}

(This script is complete, it should run "as is")

Here camel case refers to "upper camel case" aka pascal case e.g. CamelCase. If you'd like instead to use lower camel case e.g. camelCase, it should be trival to modify the to_camel funciton above.

Alias Precedence🔗

Aliases defined on the Config class of child models will take priority over any aliases defined on Config of a parent model:

from pydantic import BaseModel

class Voice(BaseModel):
    name: str
    language_code: str

    class Config:
        def alias_generator(cls, string: str) -> str:
            # this is the same as `alias_generator = to_camel` above
            return ''.join(word.capitalize() for word in string.split('_'))

class Character(Voice):
    mood: str

    class Config:
        fields = {'mood': 'Mood', 'language_code': 'lang'}

c = Character(Mood='happy', Name='Filiz', lang='tr-TR')
#> name='Filiz' language_code='tr-TR' mood='happy'
    'Name': 'Filiz',
    'lang': 'tr-TR',
    'Mood': 'happy',

(This script is complete, it should run "as is")

This includes when a child model uses alias_generator where the aliases of all parent model fields will be updated.