5

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

4

2 回答 2

6

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())
于 2019-11-20T16:30:17.090 回答
5

You can define a __post_init__ method that raises an error if all the fields are None:

@dataclass
class MyModel:
    field1: Optional[str] = None
    field2: Optional[str] = None
    field3: Optional[str] = None

    def __post_init__(self):
        if self.field1 is None and self.field2 is None and self.field3 is None:
            raise TypeError("Value needed for at least one field")
于 2019-11-20T17:20:50.757 回答