'How to create mutually exclusive fields in Pydantic

I am using Pydantic to model an object. How can I make two fields mutually exclusive?

For instance, if I have the following model:

class MyModel(pydantic.BaseModel):
    a: typing.Optional[str]
    b: typing.Optional[str]

I want field a and field b to be mutually exclusive. I want only one of them to be set. Is there a way to achieve that?



Solution 1:[1]

You can use pydantic.validator decorator to add custom validations.

from pydantic import BaseModel, validator

class MyModel(BaseModel):
    a: Optional[str]
    b: Optional[str]

    @validator("b", always=True)
    def mutually_exclusive(cls, v, values):
        if values["a"] is not None and v:
            raise ValueError("'a' and 'b' are mutually exclusive.")

        return v

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1