Home > Enterprise >  Validator for `bool` field fails with: value could not be parsed to a boolean
Validator for `bool` field fails with: value could not be parsed to a boolean

Time:04-11

I am using Pydantic for a data model and validation:

class Seller(BaseModel):
    seller_id: int
    display_name: str
    fulfilled_by_vender: bool

The Seller model is used as a nested field in some models. JSON or dict is being passed, where the data-type for fulfilled_by_vender is sometimes a string.

Is there any config that will enable parsing fulfilled_by_vender to check if it is a string?

I have tried using a validator, but it results in an error.

class Seller(BaseModel):
    seller_id: int
    display_name: str
    fulfilled_by_vender: bool

    @validator("fulfilled_by_vender")
    def verify_if_exists(cls, value):
        return 'Packed & shipped by Vender' in value

value could not be parsed to a boolean (type=type_error.bool)

CodePudding user response:

You can use the pre flag, which will cause the validator to be called prior to other validation:

class Seller(BaseModel):
    seller_id: int
    display_name: str
    fulfilled_by_vender: bool

    @validator("fulfilled_by_vender", pre=True)
    def verify_if_exists(cls, value):
        return 'Packed & shipped by Vender' in value
  • Related