如何遍历 Pydantic 模型中的所有字段
对于像这样的 Pydantic 模型:
pydantic_iter_fields.py
from pydantic import BaseModel, Field
class MyModel(BaseModel):
variable1: float = Field(default=1.5, help="TODO enter your description here")
variable2: str = Field(default="foobar", help="TODO enter your description here")
# These two fields will be ignored in dict()
_default_paths = ['/data/settings.yaml', './settings.yaml']
__config__ = {
"FOO": "BAR"
}
my_model = MyModel()你可以像这样遍历所有字段:
iterate_fields.py
dict(fields)这只会包含 Field() 实例,不包括 _default_paths 或 __config__。
示例输出:
output.py
{'variable1': 1.5, 'variable2': 'foobar'}If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow