I have defined a pydantic Schema with extra = Extra.allow
in Pydantic Config.
Is it possible to get a list or set of extra fields passed to the Schema separately.
For ex:
from pydantic import BaseModel as pydanticBaseModel
class BaseModel(pydanticBaseModel):
name: str
class Config:
allow_population_by_field_name = True
extra = Extra.allow
I pass below JSON:
{
"name": "Name",
"address": "bla bla",
"post": "post"
}
I need a function from pydantic
, if available which will return all extra fields passed.
like: {"address", "post"}
Pydantic extra fields behaviour was updated in their 2.0 release. Per their docs, you now don't need to do anything but set the model_config extra
field to allow
and then can use the model_extra
field or __pydantic_extra__
instance attribute to get a dict of extra fields.
from pydantic import BaseModel, Field, ConfigDict
class Model(BaseModel):
python_name: str = Field(alias="name")
model_config = ConfigDict(
extra='allow',
)
m = Model(**{"name": "Name", "address": "bla bla", "post": "post"}).model_extra
assert m == {'address': 'bla bla', 'post': 'post'}
m = Model(**{"name": "Name", "foobar": "fizz"}).__pydantic_extra__
assert m == {'foobar': 'fizz'}
m = Model(**{"name": "Name"}).__pydantic_extra__
assert m == {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With