【问题标题】:Allow null in JSON schema from Pydantic在 Pydantic 的 JSON 模式中允许 null
【发布时间】:2022-11-10 08:17:28
【问题描述】:

我试图在这个对象的 JSON 模式中允许 null :

from pydantic import BaseModel
from typing import Optional

class NextSong(BaseModel):
    song_title: Optional[str] = ...

但结果的架构如下:

'{"title": "NextSong", "type": "object", "properties": {"song_title": {"title": "Song Title", "type": "string"}}, "required": ["song_title"]}'

生成的架构不允许 song_title 的值为 null,这不是预期的,但我不确定如何指定允许 null,但该字段仍然是必需的。

【问题讨论】:

  • 你见过issue #1270吗?
  • 你能展示你的完整模型吗?
  • 显示的模型是完整的。感谢您链接问题,这有帮助。

标签: fastapi pydantic


【解决方案1】:

尝试使用 OR 符号

class NextSong(BaseModel):
    song_title: str|None = ...

注意:我使用的是 python 3.10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2022-10-07
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    相关资源
    最近更新 更多