[FIXED] Validate pydantic fields according to value in other field

Issue

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?


Solution

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



Answered By - MesRot
Answer Checked By - Terry (Python.Easybugfix Volunteer)

Related Posts

Post a Comment