Skip to content

validators called twice #254

@samuelcolvin

Description

@samuelcolvin

from @dmfigol on gitter:

I am failing to understand why validator is applied several times on the complex field:

import json
from typing import List, Dict, Any

from pydantic import BaseModel, ValidationError, validator

class DemoModel(BaseModel):
    data: Dict[str, Any] = {}

    @validator('data', pre=True, whole=True)
    def json_decode(cls, v):
        print(f'value is {v!r}, type: {type(v)}')
        if isinstance(v, str):
            try:
                return json.loads(v)
            except ValueError:
                pass
        return v

print(DemoModel(data='{"foo": {"bar": 123}}'))

# > value is '{"foo": {"bar": 123}}', type: <class 'str'>
# > value is 'foo', type: <class 'str'>
# > DemoModel data={'foo': {'bar': 123}}

I would appreciate if you could explain :) because of this I spent a lot of time debugging my code and after I found the problem, I still don't understand why it is working this way :(

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions