question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

fastapi pydantic nested models

See original GitHub issue

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"
      
    }
  ]
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

5reactions
shrutikapondecommented, Apr 14, 2021

@aaronstephenson, I solved this by adding response_model_by_alias.

@router.get("/",
            response_model=List[schemas.Command],
            response_model_by_alias=False)
4reactions
paloderosacommented, Mar 3, 2021

@grillazz I actually came up today to the need to implement this functionality in a many-to-many relationship. Here is my implementation of the first proposal. I will assume that you are using SQLAlchemy for ORM, that you are traversing the entities relationships through relationship model attributes and that you have initialized the declarative Base class somewhere.

import functools
from typing import Any, List

from pydantic import BaseModel, Field
from pydantic.utils import GetterDict
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship


# implementation of a recursive getattr
# taken from https://stackoverflow.com/a/31174427
def rgetattr(obj, attr, *args):
    def _getattr(obj, attr):
        return getattr(obj, attr, *args)
    return functools.reduce(_getattr, [obj] + attr.split('.'))


class NestedGetterDict(GetterDict):
    def __getitem__(self, key: str) -> Any:
        try:
            return rgetattr(self._obj, key)
        except AttributeError as e:
            raise KeyError(key) from e

    def get(self, key: Any, default: Any = None) -> Any:
        return rgetattr(self._obj, key, default)


class Container(Base):
    __tablename__ = 'container'
    ...
    container_status = relationship("ContainerStatus", lazy='joined')

class ContainerStatus(Base):
    __tablename__ = 'container_status'
    ...
    description = Column(String, nullable=False)


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

    class Config:
        orm_mode = True
        allow_population_by_field_name = True
        getter_dict = NestedGetterDict


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

This should result in what you are looking for.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Body - Nested Models - FastAPI
Each attribute of a Pydantic model has a type. But that type can itself be another Pydantic model. So, you can declare deeply...
Read more >
Define a Pydantic (nested) model - python - Stack Overflow
You have a whole part explaining the usage of pydantic with fastapi here. to respond more precisely to your question pydantic models are ......
Read more >
Using ormar in responses
Nested models excludes ... Despite the fact that fastapi allows passing only set of field names, so simple excludes, when using response_model_exclude ,...
Read more >
tiangolo/fastapi - Gitter
I need to know how to get nested models, while performing get method from a sql query. ... import asyncio import aiosql import...
Read more >
How to Make the Most of Pydantic - Towards Data Science
The structure defines a cat entry with a nested definition of an address. So then, defining a Pydantic model to tackle this could...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found