1

I'm trying to make sure one of my objects used is always in a correct state. For this I should validate not only on creation but also on assignment, and also on the sub field assignments. Here is a basic example:

from typing import Optional

from pydantic import BaseModel, root_validator


class SubModel(BaseModel):
    class Config:
        validate_assignment = True

    min: Optional[int]
    max: Optional[int]


class TestModel(BaseModel):
    class Config:
        validate_assignment = True

    field_1: Optional[SubModel]

    @root_validator
    def validate(cls, values):
        field = values.get("field_1")
        if field and field.min and field.max:
            if field.min > field.max:
                raise ValueError("error")
        return values

If I now call

model = TestModel(field_1=SubModel(min=2, max=1))

or

model = TestModel()
field_1 = SubModel(min=2, max=1)

the validation is triggered and the ValueError is raised, which is fine.

But if I do the following

model = TestModel()
field_1 = SubModel()
field_1.min = 2
field_1.max = 1

no validation is triggered.

I know that I could do the validation on SubModel level but in my case (which is a little bit more complex than the basic code shows) I don't want every object of type SubModel to have min <= max but only the one field used in TestModel. Therefor moving the validator to the SubModel is no option for me. Does anyone have an idea on how to trigger the validator of TestModel when assigning min and max on field_1?

Thank you in advance!

maria
  • 11
  • 1
  • Maybe you already found the solution, you can [set this option in a config object](https://stackoverflow.com/q/67025733/289784). – suvayu Dec 07 '22 at 15:30

0 Answers0