larick
larick

Reputation: 168

Parse flat data into nested pydantic model

I have two models:

from pydantic import BaseModel


class Nested(BaseModel):
    id: int
    title: str


class Model(BaseModel):
    id: int
    nested_id: int
    nested: Nested

Model references Nested.

I make a query with a JOIN to my database and get something like this response:

data = {'id': 5, 'nested_id': 1, 'id_1': 1, 'title': 'хлеб'}

I would like to parse this response and assign the right fields to the Nested model,

Are there any methods in BaseModel, with which I can parse data?

Of course I can work with dict which I already have. But I want to do it in a method of BaseModel .

I use parse_as_obj(List[Model], data).

Upvotes: 2

Views: 878

Answers (1)

Daniil Fajnberg
Daniil Fajnberg

Reputation: 18388

Something like this?

from pydantic import BaseModel, root_validator


DataDict = dict[str, object]


class Nested(BaseModel):
    id: int
    title: str


class Model(BaseModel):
    id: int
    nested_id: int
    nested: Nested

    @root_validator(pre=True)
    def parse_flat_nested_data(cls, values: DataDict) -> DataDict:
        if "nested" not in values:
            values["nested"] = {
                "id": values.get("id_1"),
                "title": values.get("title"),
            }
        return values


if __name__ == "__main__":
    data = {"id": 5, "nested_id": 1, "id_1": 1, "title": "хлеб"}
    instance = Model.parse_obj(data)
    print(instance)

Output: id=5 nested_id=1 nested=Nested(id=1, title='хлеб')

See documentation on validators for more.

Upvotes: 2

Related Questions