casualprogrammer
casualprogrammer

Reputation: 363

pydantic values not present


class Foo(BaseModel):
    a: str
    b: str

    @validator('a')
    def a_valid(cls, v, values):
        print(values)
        return v

Foo(a='a', b='b')
# prints '{}'

When I try to access other values in the model, Im getting an empty dictionary. I'm expecting a dict containing the name-to-value mapping of any previously-validated fields

Perhaps Im miss understanding what previously-validated fields means

Upvotes: -1

Views: 953

Answers (1)

larsks
larsks

Reputation: 312400

Fields are processed in the order in which they are defined in youyr model. When a is being validated, b hasn't been set yet. If you need to have access to other fields, you probably want a root_validator:

from pydantic import BaseModel, root_validator


class Foo(BaseModel):
    a: str
    b: str

    @root_validator
    def a_valid(cls, values):
        print(values)
        return values


Foo(a="a", b="b")
# prints '{'a': 'a', 'b': 'b'}'

Alternatively, you can change the order of the fields in your mode:

from pydantic import BaseModel, validator


class Foo(BaseModel):
    b: str
    a: str

    @validator("a")
    def a_valid(cls, v, values):
        print(values)
        return values


Foo(a="a", b="b")
# prints '{'b': 'b'}'

Upvotes: 2

Related Questions