Pydantic: Support validation of extra fields

Created on 11 May 2019  路  3Comments  路  Source: samuelcolvin/pydantic


Feature Request

It would be nice if validators could be called for extra fields when Config.extra is allow:

class Foo(BaseModel):
    class Config:
        extra = "allow"

    a: int

    @validator("*", extra=True)  # Possible API, could be opt-out instead but that might be a breaking change
    def extra_validator(...):
        ...

Foo(a=1, b={}) # extra_validator gets called for both a and b

My specific use case for this is that I want to transform extra dict fields to objects:

class Foo(BaseModel):
    class Config:
        extra = "allow"

    @validator("*", extra=True)
    def convert_extra(cls, value, field): # Not sure how field would work, but the name needs to be passed somehow
        return Foo.parse_obj(value)
feature request help wanted

Most helpful comment

I'm in favour of @validator("__extra__"), but I would have expected @validator("*") also applies to extra fields. Do you agree @samuelcolvin?

All 3 comments

Agree it would be useful.

Perhaps @validator('__extra__') would be clearer?

Happy to accept a PR.

I'm in favour of @validator("__extra__"), but I would have expected @validator("*") also applies to extra fields. Do you agree @samuelcolvin?

That would need to wait for v2, but yes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vvoody picture vvoody  路  3Comments

AlbertMukhammadiev picture AlbertMukhammadiev  路  3Comments

iwoloschin picture iwoloschin  路  3Comments

sbv-trueenergy picture sbv-trueenergy  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments