Jeet Patel
Jeet Patel

Reputation: 1241

Either of the two Pydantic attributes should be optional

I want validate a payload schema & I am using Pydantic to do that. The class created by inheriting Pydantic's BaseModel is named as PayloadValidator and it has two attributes, addCustomPages which is list of dictionaries & deleteCustomPages which is a list of strings.

class NestedCustomPages(BaseModel):
    """This is the schema for each custom page."""

    html: str
    label: str
    type: int

class PayloadValidator(BaseModelWithContext):
    """This class defines the payload load schema and also validates it."""

    addCustomPages: Optional[List[NestedCustomPages]]
    deleteCustomPages: Optional[List[str]]

I want to declare either of the attributes of class PayloadValidator as optional. I have tried looking for the solution for this but couldn't find anything.

Upvotes: 5

Views: 4349

Answers (1)

Nick
Nick

Reputation: 141

There was a question on this a while ago on the pydantic Github page: https://github.com/samuelcolvin/pydantic/issues/506. The conclusion there includes a toy example with a model that requires either a or b to be filled by using a validator:

from typing import Optional
from pydantic import validator
from pydantic.main import BaseModel


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

    @validator('b', always=True)
    def check_a_or_b(cls, b, values):
        if not values.get('a') and not b:
            raise ValueError('Either a or b is required')
        return b


mm = MyModel()

Upvotes: 7

Related Questions