python type_error ai_generated true

pydantic.errors.PydanticSchemaGenerationError: 无法为 <class 'decimal.Decimal'> 生成 pydantic-core schema。请在 model_config 中设置 arbitrary_types_allowed=True 或实现 __get_pydantic_core_schema__。

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'decimal.Decimal'>. 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.

ID: python/pydantic-arbitrary-types-schema-generation

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-02-08首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

字段类型是 Pydantic v2 无法识别的自定义类或第三方类型,且未注册对应的 core schema。

English

The field type is a custom class (or a third-party type) that Pydantic v2 does not know how to validate, and no core schema has been registered.

generic

解决方案

  1. 95% 成功率
    from pydantic import BaseModel, ConfigDict
    class Foo(BaseModel):
        model_config = ConfigDict(arbitrary_types_allowed=True)
        value: MyCustomClass
  2. 90% 成功率
    from pydantic import GetCoreSchemaHandler
    from pydantic_core import core_schema
    class MyCustomClass:
        @classmethod
        def __get_pydantic_core_schema__(cls, source, handler):
            return core_schema.no_info_plain_validator_function(cls.validate)
  3. 85% 成功率
    from typing import Annotated
    from pydantic import BeforeValidator
    MyType = Annotated[decimal.Decimal, BeforeValidator(lambda v: decimal.Decimal(str(v)))]

无效尝试

常见但无效的做法:

  1. 55% 失败

    Pydantic v2 uses model_config = ConfigDict(...); the inner Config class is deprecated and ignored in strict v2 builds.

  2. 70% 失败

    Disables validation entirely, so invalid instances pass silently and errors surface later in business logic.

  3. 85% 失败

    NewType is a static-typing alias; at runtime it is just the underlying type and does not register a schema.