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

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

版本兼容性

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

根因分析

字段使用了没有内置 pydantic-core schema 的类型(自定义类、Decimal 子类、numpy dtype 等)。

English

A field uses a type (custom class, Decimal subclass, numpy dtype) that has no built-in pydantic-core schema.

generic

解决方案

  1. 88% 成功率
    from pydantic import BaseModel, ConfigDict
    class M(BaseModel):
        model_config = ConfigDict(arbitrary_types_allowed=True)
        amount: Decimal
  2. 82% 成功率
    from typing import Annotated
    from pydantic import BaseModel, PlainSerializer
    from decimal import Decimal
    Amt = Annotated[Decimal, PlainSerializer(lambda d: str(d), return_type=str)]
    class M(BaseModel):
        amount: Amt

无效尝试

常见但无效的做法:

  1. 50% 失败

    Disables validation and serialization; JSON schema loses type info.

  2. 60% 失败

    Loses type guarantees; callers must re-parse everywhere.

  3. 75% 失败

    Breaks all other models and is not supported across pydantic minor versions.