Pydantic: How to make fields required based on other's value

Created on 23 Sep 2020  路  2Comments  路  Source: samuelcolvin/pydantic

I have a schema with a submodel with an enabled flag.
If this flag is set to true all fields of that submodel are required.
If this flag is set to false no of the other fields of that submodel have to be filled, thus they are all optional.

What's the best approach to this?
I've already tried a bit with @validator but didn't really come up with a clean solution.
Maybe I'm also missing something and something like this is really easily achievable.

question

Most helpful comment

My typical approach to coupled properties is to use a compound model, something like this:

from typing import Literal, Optional, Union
from pydantic import BaseModel

class EnabledFoo(BaseModel):
    enabled: Literal[True]
    a: str
    b: int

class DisabledFoo(BaseModel):
    enabled: Literal[False]
    a: Optional[str]
    b: Optional[int]

Foo = Union[EnabledFoo, DisabledFoo]

All 2 comments

My typical approach to coupled properties is to use a compound model, something like this:

from typing import Literal, Optional, Union
from pydantic import BaseModel

class EnabledFoo(BaseModel):
    enabled: Literal[True]
    a: str
    b: int

class DisabledFoo(BaseModel):
    enabled: Literal[False]
    a: Optional[str]
    b: Optional[int]

Foo = Union[EnabledFoo, DisabledFoo]

@patrickkwang Yep. Using this approach as well now.
I think the issue can be closed.

Was this page helpful?
0 / 5 - 0 ratings