You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSON Schema中配置生成含Literal的Pydantic模型?

修改JSON Schema以生成使用Literal的Pydantic 2.x模型

问题根源是JSON Schema中的const字段,datamodel-code-generator 0.22.0针对Pydantic 2.x的适配逻辑里,会把const转换为Pydantic 2.x已移除的const=True参数。要生成符合要求的Literal类型代码,只需将const替换为仅包含目标固定值的enum数组即可。

修改后的JSON Schema

{
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "status": {
      "enum": ["active"],
      "type": "string"
    }
  },
  "required": [
    "name",
    "status"
  ],
  "title": "MyBaseModel",
  "type": "object"
}

生成的正确Pydantic模型代码

运行datamodel-code-generator后会生成如下代码:

from __future__ import annotations

from typing import Literal

from pydantic import BaseModel, Field


class MyBaseModel(BaseModel):
    name: str = Field(..., title='Name')
    status: Literal['active']

该代码使用Pydantic 2.x支持的Literal类型定义固定值约束,导入时不会再触发const参数相关的错误。

内容的提问来源于stack exchange,提问作者shane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:45:06