Pydantic如何让必填字段在生成的JSON Schema中允许null值
解决方案
问题根因
你原有写法中Optional[str] = ...仅在Python层面标识该字段值可以为str或None、且为必填项(传参时不可省略该字段),但Pydantic默认生成JSON Schema时不会自动将null加入该字段的允许类型列表,因此生成的Schema不符合预期。
Pydantic V2 实现方案(当前主流版本)
直接通过Field的nullable参数显式声明字段值允许为null即可:
from pydantic import BaseModel, Field from typing import Optional class NextSong(BaseModel): song_title: Optional[str] = Field(..., nullable=True)
Pydantic V1 实现方案
V1版本没有内置nullable参数,需要通过schema_extra手动指定Schema的类型列表:
from pydantic import BaseModel, Field from typing import Optional class NextSong(BaseModel): song_title: Optional[str] = Field(..., schema_extra={"type": ["string", "null"]})
最终生成的符合要求的JSON Schema示例
{ "title": "NextSong", "type": "object", "properties": { "song_title": { "title": "Song Title", "type": ["string", "null"] } }, "required": ["song_title"] }
该Schema满足需求:必须传递song_title字段,字段值允许为字符串或null。
内容的提问来源于stack exchange,提问作者aleph-null
相关产品推荐
相关产品推荐

