跳到内容

RootModel

RootModel 类和类型定义。

RootModel

RootModel(
    root: RootModelRootType = PydanticUndefined, **data
)

基类: BaseModel, Generic[RootModelRootType]

用于模型根对象的 Pydantic BaseModel

属性

名称 类型 描述
root RootModelRootType

模型的根对象。

__pydantic_root_model__

模型是否为 RootModel。

__pydantic_private__

模型中的私有字段。

__pydantic_extra__

模型中的额外字段。

源代码位于 pydantic/root_model.py
63
64
65
66
67
68
69
70
71
def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None:  # type: ignore
    __tracebackhide__ = True
    if data:
        if root is not PydanticUndefined:
            raise ValueError(
                '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
            )
        root = data  # type: ignore
    self.__pydantic_validator__.validate_python(root, self_instance=self)

model_construct classmethod

model_construct(
    root: RootModelRootType,
    _fields_set: set[str] | None = None,
) -> Self

使用提供的根对象创建新模型并更新字段集合。

参数

名称 类型 描述 默认值
root RootModelRootType

模型的根对象。

必需
_fields_set set[str] | None

要更新的字段集合。

None

返回

类型 描述
Self

新模型。

抛出

类型 描述
NotImplemented

如果模型不是 RootModel 的子类。

源代码位于 pydantic/root_model.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@classmethod
def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self:  # type: ignore
    """Create a new model using the provided root object and update fields set.

    Args:
        root: The root object of the model.
        _fields_set: The set of fields to be updated.

    Returns:
        The new model.

    Raises:
        NotImplemented: If the model is not a subclass of `RootModel`.
    """
    return super().model_construct(root=root, _fields_set=_fields_set)

model_dump

model_dump(
    *,
    mode: Literal["json", "python"] | str = "python",
    include: Any = None,
    exclude: Any = None,
    context: dict[str, 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,
    serialize_as_any: bool = False
) -> Any

包含此方法仅为了为类型检查器获得更准确的返回类型。它包含在 `if TYPE_CHECKING:` 代码块中,因为实际上不需要重写。

有关参数的更多详细信息,请参阅 BaseModel.model_dump 的文档。

通常,此方法将具有 `RootModelRootType` 的返回类型,假设 `RootModelRootType` 不是 `BaseModel` 子类。如果 `RootModelRootType` 是 `BaseModel` 子类,则返回类型很可能是 `dict[str, Any]`,因为 `model_dump` 调用是递归的。在自定义序列化器的情况下,返回类型甚至可能有所不同。因此,此处使用 `Any` 来捕获所有这些情况。

源代码位于 pydantic/root_model.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def model_dump(  # type: ignore
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: Any = None,
    exclude: Any = None,
    context: dict[str, 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,
    serialize_as_any: bool = False,
) -> Any:
    """This method is included just to get a more accurate return type for type checkers.
    It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.

    See the documentation of `BaseModel.model_dump` for more details about the arguments.

    Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is
    not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return
    type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could
    even be something different, in the case of a custom serializer.
    Thus, `Any` is used here to catch all of these cases.
    """
    ...