Validation based on previous attribute #2351
-
Hi. 👋🏾 Is there a way to validate an attribute based on a previous one? E.g: from pydantic import BaseModel, validator
from typing import Optional
class Customer(BaseModel):
...
wantsJuice: bool
typeOfJuice: Optional[str] = None
@validator("typeOfJuice")
def check_type_of_juice_is_defined_if_wants_juice(cls, val):
# if wantsJuice is True, typeOfJuice must be defined
# else, ignore value of typeOfJuice I've tried to access the Thanks for the awesome lib!! 🚀 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Hi @mfrata and welcome! You can have a look at the doc, which contains an example with class Customer(BaseModel):
wantsJuice: bool
typeOfJuice: Optional[str] = None
@validator("typeOfJuice", always=True)
def check_type_of_juice_is_defined_if_wants_juice(cls, val, values):
if values.get('wantsJuice') and val is None:
raise ValueError('typeOfJuice can not be None')
return val Hope it helps 😃 |
Beta Was this translation helpful? Give feedback.
-
First discussion 👌 |
Beta Was this translation helpful? Give feedback.
-
Hi @PrettyWood and @samuelcolvin. It worked like a charm! Thanks a lot. You guys rock!! |
Beta Was this translation helpful? Give feedback.
Hi @mfrata and welcome!
You can have a look at the doc, which contains an example with
values
that contain the values already checked. Furthermore you probably want to usealways=True
to check the default value (in your caseNone
).Putting everything together you get
Hope it helps 😃