python data_error ai_generated true

pydantic.errors.PydanticInvalidForJsonSchema: 无法为核心模式 IsInstanceSchema (<class 'decimal.Decimal'>) 生成 JsonSchema

pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'decimal.Decimal'>)

ID: python/pydantic-json-schema-generation-error

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

版本兼容性

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

根因分析

字段使用了没有定义 JSON Schema 表示的任意 Python 类型(通过 arbitrary_types_allowed 或自定义类),导致 model_json_schema() 失败。

English

A field uses an arbitrary Python type (via arbitrary_types_allowed or a custom class) that has no defined JSON Schema representation, so model_json_schema() fails.

generic

解决方案

  1. 90% 成功率
    from typing import Annotated
    from pydantic import BaseModel, WithJsonSchema
    
    class Model(BaseModel):
        amount: Annotated[Decimal, WithJsonSchema({'type': 'string', 'format': 'decimal'})]
  2. 88% 成功率
    class Model(BaseModel):
        amount: float  # or str; convert to Decimal in business logic

无效尝试

常见但无效的做法:

  1. 70% 失败

    Returns an empty schema, breaking OpenAPI docs and client generation downstream.

  2. 80% 失败

    This allows the type at validation time but does not teach Pydantic how to serialize it to JSON Schema.