Please complete:
I'd like to skip fields that don't pass validation instead of throwing a ValidationError. If a field is defined as an int with a default value of None, I'd like to assign a value of None to that field if its value is not a valid int.
Here's how I'm accomplishing this now:
from pydantic import BaseModel, validator
class Thing(BaseModel):
id: str
total: int = None
@validator('total', pre=True)
def skip_invalid_ints(cls, value):
try:
return int(value)
except (TypeError, ValueError):
pass
def main():
thing1 = Thing.parse_obj(dict(id='foo'))
assert thing1.total is None
thing2 = Thing.parse_obj(dict(id='foo', total=5))
assert thing2.total == 5
thing3 = Thing.parse_obj(dict(id='foo', total='bar'))
assert thing3.total is None
thing4 = Thing.parse_obj(dict(id='foo', total=None))
assert thing4.total is None
if __name__ == '__main__':
main()
My question is, is there an easier way to do this? Some Config setting maybe?
Entirely possible, but you need to use validate_model directly.
Here is an example.
This could do with being documented.
I tried the code in the link above, but it does not work as expected, as invalid values throw exceptions. I've written code to handle this, but it's a bit ugly, as a method is called recursively to remove the invalid values and collect the error messages. A more elegant solution would be nice to have.
That code works fine, I'm using it in production. Please explain in more detail the problem you're having.
Most helpful comment
Entirely possible, but you need to use
validate_modeldirectly.Here is an example.
This could do with being documented.