BaseModel — A base class for creating Pydantic models with validation and serialization.
| Use Case | Command | Description |
|---|---|---|
| 📦 Create a model | class User(BaseModel): name: str; age: int | Define a data model with typed fields |
| ✅ Validate data | User.model_validate(data) | Validate and create a model instance from a dict |
| 📄 Parse JSON | User.model_validate_json(json_str) | Validate and create a model from a JSON string |
| 📤 Serialize to dict | user.model_dump() | Convert model to a Python dictionary |
| 📤 Serialize to JSON | user.model_dump_json() | Convert model to a JSON string |
| 📋 Generate JSON Schema | User.model_json_schema() | Generate JSON Schema for the model |
| 🔧 Construct without validation | User.model_construct(name='x', age=1) | Create instance from trusted data (no validation) |
| 📋 Get fields set | user.model_fields_set | Get set of fields explicitly set on the instance |
| 📋 Get extra fields | user.model_extra | Get extra fields if extra='allow' |
Base class for creating Pydantic models. Provides data validation, serialization, and schema generation.
Constructor: BaseModel(**data: Any) -> None
__init__(self, /, **data: Any) -> None
Create a new model by parsing and validating input data from keyword arguments.
ValidationError if the input data cannot be validated to form a valid modelself is explicitly positional-only to allow self as a field name__class_vars__ — The names of the class variables defined on the model__private_attributes__ — Metadata about the private attributes of the model__signature__ — The synthesized __init__ Signature of the model__pydantic_complete__ — Whether model building is completed, or if there are still undefined fields__pydantic_core_schema__ — The core schema of the model__pydantic_custom_init__ — Whether the model has a custom __init__ function__pydantic_decorators__ — Metadata containing the decorators defined on the model (replaces V1's Model.__validators__ and Model.__root_validators__)__pydantic_generic_metadata__ — Metadata about generic Pydantic models (origin, args, parameter)__pydantic_parent_namespace__ — Parent namespace of the model, used for automatic rebuilding__pydantic_post_init__ — The name of the post-init method for the model, if defined__pydantic_root_model__ — Whether the model is a RootModel__pydantic_serializer__ — The pydantic-core SchemaSerializer used to dump instances__pydantic_validator__ — The pydantic-core SchemaValidator used to validate instances__pydantic_fields__ — Dictionary of field names and their FieldInfo objects__pydantic_computed_fields__ — Dictionary of computed field names and their ComputedFieldInfo objects__pydantic_extra__ — Dictionary containing extra values if extra='allow'__pydantic_fields_set__ — Names of fields explicitly set during instantiation__pydantic_private__ — Values of private attributes set on the model instance__copy__(self) -> Self — Returns a shallow copy of the model__deepcopy__(self, memo: dict[int, Any] | None = None) -> Self — Returns a deep copy of the model__delattr__(self, item: str) -> Any — Implement delattr(self, name)__eq__(self, other: Any) -> bool — Return self==value__getattr__(self, item: str) -> Any__getstate__(self) -> dict[Any, Any]__iter__(self) -> TupleGenerator — So dict(model) works__pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any] — Used by devtools to pretty print objects__replace__(self, **changes: Any) -> Self — Synthesized by @dataclass_transform()__repr__(self) -> str — Return repr(self)__repr_args__(self) -> _repr.ReprArgs__repr_name__(self) -> str — Name of the instance's class, used in __repr____repr_recursion__(self, object: Any) -> str — Returns the string representation of a recursive object__repr_str__(self, join_str: str) -> str__rich_repr__(self) -> RichReprResult — Used by Rich to pretty print objects__setattr__(self, name: str, value: Any) -> None — Implement setattr(self, name, value)__setstate__(self, state: dict[Any, Any]) -> None__str__(self) -> str — Return str(self)copy(self, *, include=None, exclude=None, update=None, deep=False) -> Self
⚠️ Deprecated: Use model_copy instead.
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)
include — Optional set or mapping specifying which fields to includeexclude — Optional set or mapping specifying which fields to excludeupdate — Optional dictionary of field-value pairs to overridedeep — If True, values of fields that are Pydantic models will be deep-copieddict(self, *, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False) -> Dict[str, Any]
json(self, *, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) -> str
model_copy(self, *, update=None, deep=False) -> Self
Returns a copy of the model. The underlying __dict__ attribute is copied (may have side effects with cached properties).
update — Values to change/add in the new model (not validated)deep — Set to True to make a deep copymodel_dump(self, *, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, polymorphic_serialization=None) -> dict[str, Any]
Generate a dictionary representation of the model.
mode — 'json' for JSON-serializable types only, 'python' for any Python objectsinclude — Set of fields to include in the outputexclude — Set of fields to exclude from the outputcontext — Additional context to pass to the serializerby_alias — Whether to use field's alias in dictionary keyexclude_unset — Whether to exclude fields not explicitly setexclude_defaults — Whether to exclude fields set to their default valueexclude_none — Whether to exclude fields with value Noneexclude_computed_fields — Whether to exclude computed fieldsround_trip — If True, dumped values should be valid as input for non-idempotent typeswarnings — How to handle serialization errors (False/True/'error')fallback — Function to call when an unknown value is encounteredserialize_as_any — Whether to serialize fields with duck-typing behaviorpolymorphic_serialization — Whether to use polymorphic serializationmodel_dump_json(self, *, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, polymorphic_serialization=None) -> str
Generates a JSON representation of the model.
indent — Indentation to use in the JSON output (None = compact)ensure_ascii — If True, escape all non-ASCII charactersinclude — Field(s) to include in the JSON outputexclude — Field(s) to exclude from the JSON outputcontext — Additional context to pass to the serializerby_alias — Whether to serialize using field aliasesexclude_unset — Whether to exclude fields not explicitly setexclude_defaults — Whether to exclude fields set to their default valueexclude_none — Whether to exclude fields with value Noneexclude_computed_fields — Whether to exclude computed fieldsround_trip — If True, dumped values should be valid as input for non-idempotent typeswarnings — How to handle serialization errorsfallback — Function to call when an unknown value is encounteredserialize_as_any — Whether to serialize fields with duck-typing behaviorpolymorphic_serialization — Whether to use polymorphic serializationmodel_post_init(self, context: Any, /) -> None
Override to perform additional initialization after __init__ and model_construct. Useful for validation that requires the entire model to be initialized.
__class_getitem__(typevar_values) -> type[BaseModel] | PydanticRecursiveRef__get_pydantic_core_schema__(source, handler) -> CoreSchema__get_pydantic_json_schema__(core_schema, handler) -> JsonSchemaValue — Hook into generating the model's JSON schema__pydantic_init_subclass__(**kwargs) -> None — Called by ModelMetaclass after basic class initialization is complete__pydantic_on_complete__() -> None — Called once the class and its fields are fully initialized and ready to be usedconstruct(_fields_set=None, **values) -> Selffrom_orm(obj: Any) -> Selfmodel_construct(_fields_set=None, **values) -> Self — Creates a new instance with validated data from trusted/pre-validated datamodel_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') -> dict[str, Any] — Generates a JSON schema for a model classmodel_parametrized_name(params) -> str — Compute the class name for parametrizations of generic classesmodel_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) -> bool | None — Try to rebuild the pydantic-core schema for the modelmodel_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) -> Self — Validate a pydantic model instancemodel_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) -> Self — Validate the given JSON data against the Pydantic modelmodel_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) -> Self — Validate the given object with string data against the Pydantic modelparse_file(path, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False) -> Selfparse_obj(obj: Any) -> Selfparse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False) -> Selfschema(by_alias=True, ref_template='#/$defs/{model}') -> Dict[str, Any]schema_json(*, by_alias=True, ref_template='#/$defs/{model}', **dumps_kwargs) -> strupdate_forward_refs(**localns: Any) -> Nonevalidate(value: Any) -> Self__fields_set__model_extra — Get extra fields set during validation. Returns a dict of extra fields, or None if config.extra is not "allow".model_fields_set — Returns the set of fields that have been explicitly set on this model instance (not filled from defaults).__dict__ — Dictionary for instance variables (if defined)__pydantic_extra____pydantic_fields_set____pydantic_private____abstractmethods__ = frozenset()__annotations__ = {}__hash__ = None__pydantic_complete__ = False__pydantic_core_schema__ = MockCoreSchema__pydantic_decorators__ = DecoratorInfos(...)__pydantic_parent_namespace__ = None__pydantic_root_model__ = False__pydantic_serializer__ = MockValSer__pydantic_validator__ = MockValSermodel_computed_fields = {}model_config = {}model_fields = {}Generated by phpman v4.9.27-5-g2cb901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-20 04:07 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format