Pydantic: Skip values that don't pass validation

Created on 24 Oct 2019  路  3Comments  路  Source: samuelcolvin/pydantic

Question

Please complete:

  • OS: macOS 10.14.6
  • Python version: 3.7.4
  • Pydantic version: 1.0

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?

documentation question

Most helpful comment

Entirely possible, but you need to use validate_model directly.

Here is an example.

This could do with being documented.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dconathan picture dconathan  路  3Comments

nav picture nav  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments

drpoggi picture drpoggi  路  3Comments

vvoody picture vvoody  路  3Comments