[Python] Serialize nested Pydantic model as a single value

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say I have this Id class:

    class Id(BaseModel):
    value: Optional[str]


    The main point in this class, is that it serialized into one singular value (mostly string).

    And I use that model inside another model:

    class Item(BaseModel):
    id: Id
    name: str


    Everything works alright here. But when I generate the dict of an Item instance, it is generated like this:

    {'id': {'value': 'my id here'}, 'name': 'my name'}


    Same thing for the json generation.

    I want it to be generated like this:

    {'id': 'my id here', 'name': 'my name'}


    And still keep the same models. How do I do that?

    Continue reading...

Compartilhe esta Página