connorvo
connorvo

Reputation: 821

Pass an extra value to a class in Pydantic when initializing from API data

Pretty new to using Pydantic, but I'm currently passing in the json returned from the API to the Pydantic class and it nicely decodes the json into the classes without me having to do anything.

However, I now want to pass an extra value from a parent class into the child class upon initialization, but I can't figure out how.

In the example below, I want to pass the id of the parent to the child class.

json data example returned from api

{
    "id": "162172481",
    "filed_at": "2022-11-12",
    "child": {
        "items": ["item1", "item2", "item3"]   
    }
}

pydantic class

class ExampleA(BaseModel):
    class ChildA(BaseModel):
        parent_id: str # how do I pass this in
        items: list[str]

    id: str
    filed_at: date = Field(alias="filedAt")
    child: ChildA

    class Config:
        allow_population_by_field_name = True

initializing the data

data = API.get_example_data()
example_class = ExampleA(**data)

Upvotes: 1

Views: 2429

Answers (1)

Plagon
Plagon

Reputation: 3139

I don't think that there is a way around doing it yourself. But I think the most elegant way is to use a validator.

class ExampleA(BaseModel):
    class ChildA(BaseModel):
        parent_id: str  # how do I pass this in
        items: list[str]

    id: str
    filed_at: date = Field(alias="filedAt")
    child: ChildA

    @validator('child', pre=True)
    def inject_id(cls, v, values):
        v['parent_id'] = values['id']
        return v

    class Config:
        allow_population_by_field_name = True

The important part is pre=True so that validator is run before the child gets initialized.

Upvotes: 2

Related Questions