I have written few classes for my data parsing. Data is the dict with very big depth and lots of string values (numbers, dates, bools) are all strings. With data which is presented there is no problems and type conversion works well. But with "empty" values ("" ones) I get validation error. I was trying to write validator but unsuccessfully. How should I realize that?
class Amount(BaseModel):
amt: float = 0
cur: int = 0
@validator("amt", "cur")
def check_str(cls, x):
if x == "":
return 0
else:
return x
d = Amount.parse_obj({"amt": "", "cur": ""})
2 validation errors for Amount
amt
value is not a valid float (type=type_error.float)
cur
value is not a valid integer (type=type_error.integer)
P.S. writing try-except
construction in main body is no use, because Amount
class is only a little subclass of much greater construction
CodePudding user response:
You need to add pre=True
to your validator:
class Amount(BaseModel):
amt: float = 0
cur: int = 0
@validator("amt", "cur", pre=True)
def check_str(cls, x):
if x == "":
return 0
else:
return x
d = Amount.parse_obj({"amt": "", "cur": ""})
References
https://pydantic-docs.helpmanual.io/usage/validators/#pre-and-per-item-validators