Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get incoming extra fields from Pydantic?

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"}

like image 512
Jyotirmay Avatar asked Aug 31 '25 15:08

Jyotirmay


1 Answers

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 == {}
like image 78
robcxyz Avatar answered Sep 04 '25 01:09

robcxyz