BaseModel
A base class for creating Pydantic models.
Configuration for the model, should be a dictionary conforming to ConfigDict.
Type: ConfigDict Default: ConfigDict()
The core schema of the model.
Type: CoreSchema
Get extra fields set during validation.
Type: dict[str, Any] | None
Returns the set of fields that have been explicitly set on this model instance.
Type: set[str]
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.
None
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]
A mapping of field names to their respective FieldInfo instances.
dict[str, FieldInfo]
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]
A mapping of computed field names to their respective ComputedFieldInfo instances.
dict[str, ComputedFieldInfo]
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, values: Any = {}) -> Self
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.
Self — A new instance of the Model class with validated data.
A set of field names that were originally explicitly set during instantiation. If provided,
this is directly used for the model_fields_set attribute.
Otherwise, the field names from the values argument will be used.
Trusted or pre-validated data dictionary.
def model_copy(update: Mapping[str, Any] | None = None, deep: bool = False) -> Self
Returns a copy of the model.
Self — New model instance.
Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
Set to True to make a deep copy of the model.
def model_dump(
mode: Literal['json', 'python'] | str = 'python',
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> dict[str, Any]
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
dict[str, Any] — A dictionary representation of the model.
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.
A set of fields to include in the output.
A set of fields to exclude from the output.
Additional context to pass to the serializer.
Whether to use the field’s alias in the dictionary key if defined.
Whether to exclude fields that have not been explicitly set.
Whether to exclude fields that are set to their default value.
Whether to exclude fields that have a value of None.
If True, dumped values should be valid as input for non-idempotent types such as Json[T].
How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors,
“error” raises a PydanticSerializationError.
A function to call when an unknown value is encountered. If not provided,
a PydanticSerializationError error is raised.
Whether to serialize fields with duck-typing serialization behavior.
def model_dump_json(
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> str
Generates a JSON representation of the model using Pydantic’s to_json method.
str — A JSON string representation of the model.
Indentation to use in the JSON output. If None is passed, the output will be compact.
Field(s) to include in the JSON output.
Field(s) to exclude from the JSON output.
Additional context to pass to the serializer.
Whether to serialize using field aliases.
Whether to exclude fields that have not been explicitly set.
Whether to exclude fields that are set to their default value.
Whether to exclude fields that have a value of None.
If True, dumped values should be valid as input for non-idempotent types such as Json[T].
How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors,
“error” raises a PydanticSerializationError.
A function to call when an unknown value is encountered. If not provided,
a PydanticSerializationError error is raised.
Whether to serialize fields with duck-typing serialization behavior.
@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.
dict[str, Any] — The JSON schema for the given model class.
Whether to use attribute aliases or not.
The reference template.
To override the logic used to generate the JSON schema, as a subclass of
GenerateJsonSchema with your desired modifications
The mode in which to generate the schema.
@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.
str — String representing the new class where params are passed to cls as type variables.
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.
TypeError— Raised when trying to generate concrete names for non-generic models.
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.
None
@classmethod
def model_rebuild(
cls,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: MappingNamespace | 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.
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.
Whether to force the rebuilding of the model schema, defaults to False.
Whether to raise errors, defaults to True.
The depth level of the parent namespace, defaults to 2.
The types namespace, defaults to None.
@classmethod
def model_validate(
cls,
obj: Any,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Self
Validate a pydantic model instance.
Self — The validated model instance.
The object to validate.
Whether to enforce types strictly.
Whether to extract data from object attributes.
Additional context to pass to the validator.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— If the object could not be validated.
@classmethod
def model_validate_json(
cls,
json_data: str | bytes | bytearray,
strict: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Self
Validate the given JSON data against the Pydantic model.
Self — The validated Pydantic model.
The JSON data to validate.
Whether to enforce types strictly.
Extra variables to pass to the validator.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— Ifjson_datais not a JSON string or the object could not be validated.
@classmethod
def model_validate_strings(
cls,
obj: Any,
strict: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Self
Validate the given object with string data against the Pydantic model.
Self — The validated Pydantic model.
The object containing string data to validate.
Whether to enforce types strictly.
Extra variables to pass to the validator.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
def create_model(
model_name: str,
__config__: ConfigDict | None = None,
__doc__: str | None = None,
__base__: None = None,
__module__: str = __name__,
__validators__: dict[str, Callable[..., Any]] | None = None,
__cls_kwargs__: dict[str, Any] | None = None,
field_definitions: Any | tuple[str, Any] = {},
) -> type[BaseModel]
def create_model(
model_name: str,
__config__: ConfigDict | None = None,
__doc__: str | None = None,
__base__: type[ModelT] | tuple[type[ModelT], ...],
__module__: str = __name__,
__validators__: dict[str, Callable[..., Any]] | None = None,
__cls_kwargs__: dict[str, Any] | None = None,
field_definitions: Any | tuple[str, Any] = {},
) -> type[ModelT]
Dynamically creates and returns a new Pydantic model, in other words, create_model dynamically creates a
subclass of BaseModel.
type[ModelT] — The new model.
The name of the newly created model.
The configuration of the new model.
The docstring of the new model.
The base class or classes for the new model.
The name of the module that the model belongs to;
if None, the value is taken from sys._getframe(1)
A dictionary of methods that validate fields. The keys are the names of the validation methods to be added to the model, and the values are the validation methods themselves. You can read more about functional validators here.
A dictionary of keyword arguments for class creation, such as metaclass.
Field definitions of the new model. Either:
- a single element, representing the type annotation of the field.
- a two-tuple, the first element being the type and the second element the assigned value
(either a default or the
Field()function).
PydanticUserError— If__base__and__config__are both passed.