Search code examples
pydantic

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

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

    from typing import Optional
    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