Slavik21
Slavik21

Reputation: 121

How to do verification in pydantic

I need to check key in MyDict - key must be in A_list, value is free. How can i do this?

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

Upvotes: 1

Views: 1214

Answers (1)

crissal
crissal

Reputation: 2647

You can use validators. They are class methods, so values (a dictionary) must be provided after your dictionary to retrieve already validated fields of your Model - in this case, 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)
"""

Upvotes: 1

Related Questions