Skip to content

fastapi pydantic nested models #2864

@grillazz

Description

@grillazz

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

My view models below:

class EnvContainersStatusResponse(BaseModel):
    description: str = Field(...)

    class Config:
        orm_mode = True
        allow_population_by_field_name = True


class EnvContainersResponse(BaseModel):
    container_name: str = Field(alias='_name')
    container_status: EnvContainersStatusResponse

    class Config:
        orm_mode = True
        allow_population_by_field_name = True


class EnvResponse(EnvBase):
    env_id: str = Field(alias='environment_name')
    container_collection: List[EnvContainersResponse] = Field(alias='compute_node_containers')

    class Config:
        orm_mode = True
        allow_population_by_field_name = True

my response is like below

{
  "environment_name": "somenewenv",
  "compute_node_containers": [
    {
      "_name": "compute001",
      "container_status": {
        "description": "online"
      }
    }
  ]
}

question: how i can flatten my response model to have below:

want eliminate another dict and have only key value like "container_status": "online"

{
  "environment_name": "somenewenv",
  "compute_node_containers": [
    {
      "_name": "compute001",
      "container_status": "online"
      
    }
  ]
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions