0

I'd like to parse object, which initially is not corresponded to the model, means it's fields not match target schema. So I'd like to inference model values, based on other values of the raw object. In the following scenario I'd like to give foo the value of first key of src dict, just for example.

class Model(BaseModel):
    foo: int

    @validator('foo', pre=True, always=True, check_fields=False)
    def convert_foo(cls, v, values):
        v = values['src']
        assert isinstance(v, dict)
        return [*v.keys()][0]


m = Model.parse_obj({'src': {1: 2}})

and I got

pydantic.error_wrappers.ValidationError: 1 validation error for Model
foo
  field required (type=value_error.missing)

How to deal with that? Is the only option to use root validator?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anton Ovsyannikov
  • 1,010
  • 1
  • 12
  • 30

1 Answers1

1

In the scenario you proposed you cannot use @validator. From the documentation:

values: a dict containing the name-to-value mapping of any previously-validated fields

Notice the "previously-validated fields". Even if you assigned a default value to foo (foo: int = 0) to avoid the field required (type=value_error.missing), you won't be able to access src because it is not a field.

A @root_validator(pre=True), as you suggested, should work and I believe would be the usual approach.

Hernán Alarcón
  • 3,494
  • 14
  • 16