Skip to content

Validation based on previous attribute #2351

Answered by PrettyWood
mfrata asked this question in Question
Discussion options

You must be logged in to vote

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 use always=True to check the default value (in your case None).
Putting everything together you get

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 😃

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by samuelcolvin
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants