how to validate nested Model with the flattened input with Pydantic?

33 views Asked by At

support the input is

input_dict = {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3",
    "field4": "value4",
}

the models I created are(you can rewrite it, I just want to get the desired output)

class Model1(BaseModel):
    field1: str
    field2: str

class Model2(BaseModel):
    model1: Model1
    field3: str

so how to validate the input? the desired output should be:

Model2(**input_dict).model_dump()
{
    "model1": {
        "field1": "value1",
        "field2": "value2",
    },
    "field3": "value3",
}

Please feel free to ask for more details if I didn't express it clearly.

thanks in advance!!!

You can ignore the below

the background is that the flattened input is from the request body, and the desired output will be used to construct protobuf which requires the nested output.

the protobuf should be

message event2 {
    message event1 {
        str field1 = 1
        str field2 = 2
    }
    str field3 = 1
}
0

There are 0 answers