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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 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.
解决方案
-
95% 成功率
from pydantic import BaseModel, ConfigDict class Foo(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) value: MyCustomClass -
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) -
85% 成功率
from typing import Annotated from pydantic import BeforeValidator MyType = Annotated[decimal.Decimal, BeforeValidator(lambda v: decimal.Decimal(str(v)))]
无效尝试
常见但无效的做法:
-
55% 失败
Pydantic v2 uses model_config = ConfigDict(...); the inner Config class is deprecated and ignored in strict v2 builds.
-
70% 失败
Disables validation entirely, so invalid instances pass silently and errors surface later in business logic.
-
85% 失败
NewType is a static-typing alias; at runtime it is just the underlying type and does not register a schema.