Skip to content
You're viewing docs for v2.7. See the latest version →

BaseModel

BaseModel

Usage docs: https://docs.pydantic.dev/2.7/concepts/models/

A base class for creating Pydantic models.

Attributes

model_config

Configuration for the model, should be a dictionary conforming to ConfigDict.

Type: ConfigDict Default: ConfigDict()

model_computed_fields

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

Type: dict[str, ComputedFieldInfo]

model_extra

Get extra fields set during validation.

Type: dict[str, Any] | None

model_fields

Metadata about the fields defined on the model, mapping of field names to FieldInfo.

This replaces Model.__fields__ from Pydantic V1.

Type: dict[str, FieldInfo]

model_fields_set

Returns the set of fields that have been explicitly set on this model instance.

Type: set[str]

Methods

init

def __init__(data: Any = {}) -> None

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Returns

None

model_construct

@classmethod

def model_construct(
    cls: type[Model],
    _fields_set: set[str] | None = None,
    values: Any = {},
) -> Model

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Returns

Model — A new instance of the Model class with validated data.

Parameters

_fields_set : set[str] | None Default: None

The set of field names accepted for the Model instance.

values : Any Default: \{\}

Trusted or pre-validated data dictionary.

model_copy

def model_copy(update: dict[str, Any] | None = None, deep: bool = False) -> Model

Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#model_copy

Returns a copy of the model.

Returns

Model — New model instance.

Parameters

update : dict[str, Any] | None Default: None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

deep : bool Default: False

Set to True to make a deep copy of the model.

model_dump

def model_dump(
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx = None,
    exclude: IncEx = None,
    context: dict[str, Any] | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    serialize_as_any: bool = False,
) -> dict[str, Any]

Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Returns

dict[str, Any] — A dictionary representation of the model.

Parameters

mode : Literal['json', 'python'] | str Default: 'python'

The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

include : IncEx Default: None

A set of fields to include in the output.

exclude : IncEx Default: None

A set of fields to exclude from the output.

context : dict[str, Any] | None Default: None

Additional context to pass to the serializer.

by_alias : bool Default: False

Whether to use the field’s alias in the dictionary key if defined.

exclude_unset : bool Default: False

Whether to exclude fields that have not been explicitly set.

exclude_defaults : bool Default: False

Whether to exclude fields that are set to their default value.

exclude_none : bool Default: False

Whether to exclude fields that have a value of None.

round_trip : bool Default: False

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

warnings : bool | Literal['none', 'warn', 'error'] Default: True

How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors, “error” raises a PydanticSerializationError.

serialize_as_any : bool Default: False

Whether to serialize fields with duck-typing serialization behavior.

model_dump_json

def model_dump_json(
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    context: dict[str, Any] | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    serialize_as_any: bool = False,
) -> str

Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic’s to_json method.

Returns

str — A JSON string representation of the model.

Parameters

indent : int | None Default: None

Indentation to use in the JSON output. If None is passed, the output will be compact.

include : IncEx Default: None

Field(s) to include in the JSON output.

exclude : IncEx Default: None

Field(s) to exclude from the JSON output.

context : dict[str, Any] | None Default: None

Additional context to pass to the serializer.

by_alias : bool Default: False

Whether to serialize using field aliases.

exclude_unset : bool Default: False

Whether to exclude fields that have not been explicitly set.

exclude_defaults : bool Default: False

Whether to exclude fields that are set to their default value.

exclude_none : bool Default: False

Whether to exclude fields that have a value of None.

round_trip : bool Default: False

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

warnings : bool | Literal['none', 'warn', 'error'] Default: True

How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors, “error” raises a PydanticSerializationError.

serialize_as_any : bool Default: False

Whether to serialize fields with duck-typing serialization behavior.

model_json_schema

@classmethod

def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]

Generates a JSON schema for a model class.

Returns

dict[str, Any] — The JSON schema for the given model class.

Parameters

by_alias : bool Default: True

Whether to use attribute aliases or not.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The reference template.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

mode : JsonSchemaMode Default: 'validation'

The mode in which to generate the schema.

model_parametrized_name

@classmethod

def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Returns

str — String representing the new class where params are passed to cls as type variables.

Parameters

params : tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Raises
  • TypeError — Raised when trying to generate concrete names for non-generic models.

model_post_init

def model_post_init(__context: Any) -> None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Returns

None

model_rebuild

@classmethod

def model_rebuild(
    cls,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Returns

bool | None — Returns None if the schema is already “complete” and rebuilding was not required. bool | None — If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Parameters

force : bool Default: False

Whether to force the rebuilding of the model schema, defaults to False.

raise_errors : bool Default: True

Whether to raise errors, defaults to True.

_parent_namespace_depth : int Default: 2

The depth level of the parent namespace, defaults to 2.

_types_namespace : dict[str, Any] | None Default: None

The types namespace, defaults to None.

model_validate

@classmethod

def model_validate(
    cls: type[Model],
    obj: Any,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate a pydantic model instance.

Returns

Model — The validated model instance.

Parameters

obj : Any

The object to validate.

strict : bool | None Default: None

Whether to enforce types strictly.

from_attributes : bool | None Default: None

Whether to extract data from object attributes.

context : dict[str, Any] | None Default: None

Additional context to pass to the validator.

Raises
  • ValidationError — If the object could not be validated.

model_validate_json

@classmethod

def model_validate_json(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Usage docs: https://docs.pydantic.dev/2.7/concepts/json/#json-parsing

Validate the given JSON data against the Pydantic model.

Returns

Model — The validated Pydantic model.

Parameters

json_data : str | bytes | bytearray

The JSON data to validate.

strict : bool | None Default: None

Whether to enforce types strictly.

context : dict[str, Any] | None Default: None

Extra variables to pass to the validator.

Raises
  • ValueError — If json_data is not a JSON string.

copy

def copy(
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)
Returns

Model — A copy of the model with included, excluded and updated fields as specified.

Parameters

include : AbstractSetIntStr | MappingIntStrAny | None Default: None

Optional set or mapping specifying which fields to include in the copied model.

exclude : AbstractSetIntStr | MappingIntStrAny | None Default: None

Optional set or mapping specifying which fields to exclude in the copied model.

update : typing.Dict[str, Any] | None Default: None

Optional dictionary of field-value pairs to override field values in the copied model.

deep : bool Default: False

If True, the values of fields that are Pydantic models will be deep-copied.


create_model

def create_model(
    __model_name: str,
    __config__: ConfigDict | None = None,
    __doc__: str | None = None,
    __base__: None = None,
    __module__: str = __name__,
    __validators__: dict[str, classmethod] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    field_definitions: Any = {},
) -> type[BaseModel]
def create_model(
    __model_name: str,
    __config__: ConfigDict | None = None,
    __doc__: str | None = None,
    __base__: type[Model] | tuple[type[Model], ...],
    __module__: str = __name__,
    __validators__: dict[str, classmethod] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    field_definitions: Any = {},
) -> type[Model]

Usage docs: https://docs.pydantic.dev/2.7/concepts/models/#dynamic-model-creation

Dynamically creates and returns a new Pydantic model, in other words, create_model dynamically creates a subclass of BaseModel.

Returns

type[Model] — The new model.

Parameters

__model_name : str

The name of the newly created model.

__config__ : ConfigDict | None Default: None

The configuration of the new model.

__doc__ : str | None Default: None

The docstring of the new model.

__base__ : type[Model] | tuple[type[Model], ...] | None Default: None

The base class or classes for the new model.

__module__ : str | None Default: None

The name of the module that the model belongs to; if None, the value is taken from sys._getframe(1)

__validators__ : dict[str, classmethod] | None Default: None

A dictionary of methods that validate fields.

__cls_kwargs__ : dict[str, Any] | None Default: None

A dictionary of keyword arguments for class creation, such as metaclass.

__slots__ : tuple[str, ...] | None Default: None

Deprecated. Should not be passed to create_model.

**field_definitions : Any Default: \{\}

Attributes of the new model. They should be passed in the format: <name>=(<type>, <default value>), <name>=(<type>, <FieldInfo>), or typing.Annotated[<type>, <FieldInfo>]. Any additional metadata in typing.Annotated[<type>, <FieldInfo>, ...] will be ignored.

Raises

  • PydanticUserError — If __base__ and __config__ are both passed.