如何使继承自 UUID 的自定义类型作为 pydantic 模型工作

问题描述 投票:0回答:1

在我们的代码库中,我们使用自定义 UUID 类。这是它的简化版本:

class ID(uuid.UUID):
    def __init__(self, *args: Any, **kwargs: Any):
        super().__init__(*args, **kwargs)

我们不能继承

BaseModel
uuid.UUID
,因为
pydantic
会抛出错误(由于不允许多重继承)。尽管如此,按照它的定义方式,如果我们使用
pydantic
类作为
ID
模型的一部分,
pydantic
会抛出错误:

class Model(BaseModel):
    id: ID

这是我们收到的错误:

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class '__main__.ID'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.7/u/schema-for-unknown-type

我已经阅读了一些有关如何通过尝试实现错误消息建议的功能来解决此问题的内容(

__get_pydantic_core_schema__ 
)。我尝试通过将以下内容添加到
ID
类来修复它:

    @classmethod
    def __get_pydantic_json_schema__(cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler):
        return {"type": "UUID"}

    @classmethod
    def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler):
        return core_schema.no_info_plain_validator_function(uuid.UUID)

但是随后我遇到了更多错误。您知道如何正确设置吗?

python uuid pydantic
1个回答
0
投票

您可以使用RootModel:

import uuid
from pydantic import RootModel

class ID(RootModel):
    root: uuid.UUID

© www.soinside.com 2019 - 2024. All rights reserved.