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.
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.
Most helpful comment
My typical approach to coupled properties is to use a compound model, something like this: