【问题标题】:Get all required fields of a nested Python Pydantic model获取嵌套 Python Pydantic 模型的所有必填字段
【发布时间】:2023-01-18 02:07:33
【问题描述】:

我的 pydantic 嵌套模型定义如下:

from pydantic import BaseModel
from typing import Optional

class Location(BaseModel):
    city: Optional[str]
    state: str
    country: str

class User(BaseModel):
    id: int
    name: str = "Gandalf"
    age: Optional[int]
    location: Location

我想获取用户模型的所有必填字段。 对于上面的例子,预期的输出是["id", "name", "state", "country"]

非常感谢任何帮助。

【问题讨论】:

  • 但是作为输出的平面列表不清楚州和国家/地区属于嵌套的“位置”项目
  • 有一个键值对列表可以接受吗?
  • @farbiondriven 最好使用平面列表,因为我想将此列表与另一个列表进行匹配。
  • @farbiondriven 键值对也可以,谢谢
  • name 不是必填字段。如果字段有默认值,则不需要。在您的情况下,User.name 具有默认值 "Gandalf"

标签: python python-3.6 pydantic


【解决方案1】:

这是一个带有生成器函数的解决方案:

from collections.abc import Iterator


def required_fields(model: type[BaseModel], recursive: bool = False) -> Iterator[str]:
    for name, field in model.__fields__.items():
        t = field.type_
        if not field.required:
            continue
        if recursive and isinstance(t, type) and issubclass(t, BaseModel):
            yield from required_fields(t, recursive=True)
        else:
            yield name

使用您在示例中定义的模型,我们可以像这样演示它:

print(list(required_fields(User, recursive=True)))

输出:

['id', 'state', 'country']

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 2022-11-26
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2022-01-15
    • 2021-09-06
    • 2022-07-28
    • 1970-01-01
    相关资源
    最近更新 更多