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)
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.
Most helpful comment
I'm in favour of
@validator("__extra__"), but I would have expected@validator("*")also applies toextrafields. Do you agree @samuelcolvin?