#๐Ÿ”’ Hi all,

7 messages ยท Page 1 of 1 (latest)

edgy python
#

I'm learning Pydantic and I just learned about AliasPath. See the attached example.

I can't figure out how to do this the other way around, have a flat input and output a nested model where "address" holds the address-items. Any suggestions on how to do this ?

glossy lionBOT
#

@edgy python

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sinful pilot
#

Not sure, but I think you should try creating another model called Address and using it as a field in Person?

edgy python
#

Thanks for pointing me in the right direction, it works with this code:

from typing import Any
from pydantic import BaseModel, model_validator

person_data: dict[str, Any] = {
    "first_name": "Jane",
    "last_name": "Doe",
    "date_of_birth": "1990-05-15",
    "street_name": "Maple Street",
    "house_number": 42,
    "zip_code": "12345",
    "city": "Miami",
    "income": 100000,
}


class Address(BaseModel):
    street_name: str
    house_number: int
    zipcode_code: str
    city: str


class Person(BaseModel):
    first_name: str
    last_name: str
    date_of_birth: str
    address: Address
    income: int

    @model_validator(mode="before")
    def build_nested_address(cls, values: dict) -> dict:
        # Create a copy of the original flat dict for the root model
        result = values.copy()

        # Create the nested address structure using the same flat dict
        result["address"] = values

        return result


person = Person(**person_data)
print(person.model_dump_json(indent=4))
main zinc
#

@edgy python Nice one! Well done.

glossy lionBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.