I am sometimes getting data that is either a string or int for 2 of my values. Im trying to figure out the best solution for handling this and I am using pydantic v2. Ive been studying the @field_validtaors(pre=True) but haven't been successful.
Here's my code:
class User(BaseModel):
system_id: str
db_id: str
id: str
record: dict
isValid: bool
@field_validator("id", mode='before') <<<--------- not working
def transform_system_id_to_str(cls, value) -> str:
return str(value)
@field_validator("system_id", mode='before') <<<--------- not working
def transform_system_id_to_str(cls, value: str | int) -> str:
if isinstance(value, str):
print('yes')
return value
return str(value)
You can validate more than one fields in a field_validator
.
Try the following code:
class User(BaseModel):
system_id: str
db_id: str
id: str
record: dict
isValid: bool
@field_validator("id","system_id", mode='before')
def transform_id_to_str(cls, value) -> str:
return str(value)
u = User(system_id='199', db_id="1", id='99', record={}, isValid=True)
print(u) ## system_id='199' db_id='1' id='99' record={} isValid=True
u = User(system_id=199, db_id="1", id=99, record={}, isValid=True)
print(u) ## system_id='199' db_id='1' id='99' record={} isValid=True
Before validators run before Pydantic's internal parsing and validation (e.g. coercion of a str to an int). https://docs.pydantic.dev/latest/concepts/validators/