Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataclasses: Require at least one value to be set in grouping of model fields

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)?

like image 465
Joe Bane Avatar asked Jan 25 '23 14:01

Joe Bane


1 Answers

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())
like image 109
SColvin Avatar answered Jan 31 '23 10:01

SColvin