简体   繁体   中英

Validate pydantic fields according to value in other field

I'm trying to validate some field according to other fields, example:

from pydantic import BaseModel, validator
class MyClass(BaseModel):
    type: str
    field1: Optional[str] = None
    field2: Optional[str] = None
    field3: Optional[str] = None

   @validator("type")
   def has_required_fields(cls, v, values):
       required_fields {"v1": ["field1", "field3"], "v2": ["field2"]}
       for required_field in required_fields[c]:
           if not values[required_field]:
               raise Exception

But my issue is that the values dict is empty. How should I access the other fields correctly in this situation?

I believe you need to set “always=True” in the validator if you plan on type being empty when you initialize it. See here:

https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470

Fields are validated in order they are initialized. Dictionary is empty because there is no validated fields as the type is the first field to be validated.

-> Reorder the field initialization or -> Use root validator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM