How can one require at least one field in a group of fields on a dataclass to be set to a truthy value? Does this require a custom root validator method as it requires looking at many fields at once? For example, consider the following dataclass:
@dataclass
class MyModel:
field1: Optional[str]: None
field2: Optional[str]: None
field3: Optional[str]: None
How could one require at least one of these three fields (field1
, field2
, or field3
) to be set to a non-empty string? Is there some built-in way to specify at least one field must be non-nil/empty (besides a custom root validator)?
You can either user a root validator or add a validator to field3
and inspect the preceeding fields (field1
and field2
) to check one of them is set.
with root_validator
:
from typing import Optional
from pydantic import root_validator
from pydantic.dataclasses import dataclass
@dataclass
class MyModel:
field1: Optional[str] = None
field2: Optional[str] = None
field3: Optional[str] = None
@root_validator
def any_of(cls, v):
if not any(v.values()):
raise ValueError('one of field1, field2 or field3 must have a value')
return v
print(MyModel(field1='hello'))
print(MyModel(field2='goodbye'))
print(MyModel())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With