【问题标题】:How do i use nested model with none value in pydantic如何在 pydantic 中使用没有值的嵌套模型
【发布时间】:2021-08-26 18:35:53
【问题描述】:
from pydantic import BaseModel
from typing import List
class Emails(BaseModel):
    Type: int
    Value: str = None
    IsPrimary: bool

class User(BaseModel):
   Emails: List[Emails] = None

INPUT :- User('Emails': [{'Type': 0, 'Value': 'qwert@gmail.com', 'IsPrimary': true}, 
                        {'Type': 1, 'Value': 'qpoefk@outlook.com', 'IsPrimary': true}])

这里pydantic是一个python模块,Emails类继承了pydantic的BaseModel Type 是整数,Value 是字符串,IsPrimary 是布尔值。 将 json 字符串传递给类时出错

File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 4 validation errors for users_record
Emails -> 0
  value is not None (type=type_error.not_none)
Emails -> 1
  value is not None (type=type_error.not_none)
Phones -> 0
  value is not None (type=type_error.not_none)
Phones -> 1
  value is not None (type=type_error.not_none)

【问题讨论】:

  • Optional[str] 工作吗?

标签: python fastapi pydantic


【解决方案1】:

你有相同的模型名称和字段名称Emails,这会导致错误。例如,给一个不同的名称:

class User(BaseModel):
    Emails: List[Email] = None

【讨论】:

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