【问题标题】:How to do verification in pydantic如何在pydantic中进行验证
【发布时间】:2021-08-10 09:26:55
【问题描述】:

我需要检查 MyDict 中的密钥 - 密钥必须在 A_list 中,值是免费的。 我该怎么做?

from pydantic import BaseModel
from typing import List, Dict, Tuple

class Model(BaseModel):
    A_list: List[str]
    MyDict: Dict[str, str]  # 1-str is A_list

【问题讨论】:

    标签: python pydantic


    【解决方案1】:

    您可以使用validators。它们是类方法,因此必须您的字典之后提供values(字典)以检索模型的已验证字段 - 在本例中为A_list

    from pydantic import BaseModel, validator
    from typing import List, Dict, Tuple
    
    class Model(BaseModel):
        A_list: List[str]
        MyDict: Dict[str, str]  # 1-str is A_list
    
        @validator("MyDict")
        def must_be_in_list(cls, thedict, values):
            for key in thedict.keys():
                if key not in values["A_list"]:
                    raise ValueError(f"{key} not found in list!")
    
    m1 = Model(A_list=["a"], MyDict={"a": 1})  # ok
    m2 = Model(A_list=["a"], MyDict={"a": 1, "b": 2})
    """
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__
    pydantic.error_wrappers.ValidationError: 1 validation error for Model
    MyDict
      b not found in list! (type=value_error)
    """
    

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2021-08-14
      • 2018-05-11
      • 2014-05-20
      • 2021-12-04
      相关资源
      最近更新 更多