Getting nested response from self related model

I am using fastapi for the first time, and I divided my project into two parts which are admin (used django) and api (fastapi). First I defined my models in django and migrated, and connect fastapi to the existing db.
models.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Category(Base):
__tablename__ = "category"
id = Column(BigInteger, primary_key=True)
created_at = Column(DateTime(timezone=True))
updated_at = Column(DateTime(timezone=True))
icon = Column(String(100))
order = Column(Integer)
lft = Column(Integer)
rght = Column(Integer)
tree_id = Column(Integer)
level = Column(Integer)
parent_id = Column(BigInteger, ForeignKey("category.id"))
parent = relationship("Category", remote_side=[id])
translations = relationship("CategoryTranslation", back_populates="category")
class CategoryTranslation(Base):
__tablename__ = "category_translation"
id = Column(BigInteger, primary_key=True)
language_code = Column(String(15))
name = Column(String(255))
slug = Column(String(255))
master_id = Column(BigInteger, ForeignKey("category.id"))
category = relationship("Category", back_populates="translations")
</code>
<code>class Category(Base): __tablename__ = "category" id = Column(BigInteger, primary_key=True) created_at = Column(DateTime(timezone=True)) updated_at = Column(DateTime(timezone=True)) icon = Column(String(100)) order = Column(Integer) lft = Column(Integer) rght = Column(Integer) tree_id = Column(Integer) level = Column(Integer) parent_id = Column(BigInteger, ForeignKey("category.id")) parent = relationship("Category", remote_side=[id]) translations = relationship("CategoryTranslation", back_populates="category") class CategoryTranslation(Base): __tablename__ = "category_translation" id = Column(BigInteger, primary_key=True) language_code = Column(String(15)) name = Column(String(255)) slug = Column(String(255)) master_id = Column(BigInteger, ForeignKey("category.id")) category = relationship("Category", back_populates="translations") </code>
class Category(Base):
    __tablename__ = "category"

    id = Column(BigInteger, primary_key=True)
    created_at = Column(DateTime(timezone=True))
    updated_at = Column(DateTime(timezone=True))
    icon = Column(String(100))
    order = Column(Integer)
    lft = Column(Integer)
    rght = Column(Integer)
    tree_id = Column(Integer)
    level = Column(Integer)
    parent_id = Column(BigInteger, ForeignKey("category.id"))

    parent = relationship("Category", remote_side=[id])
    translations = relationship("CategoryTranslation", back_populates="category")


class CategoryTranslation(Base):
    __tablename__ = "category_translation"

    id = Column(BigInteger, primary_key=True)
    language_code = Column(String(15))
    name = Column(String(255))
    slug = Column(String(255))
    master_id = Column(BigInteger, ForeignKey("category.id"))

    category = relationship("Category", back_populates="translations")

I’m trying to retrieve nested objects from my database but I’m unsure how to efficiently query and serialize nested objects.
Here’s a router:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@router.get("/")
async def get_categories(db: Session = Depends(get_db),):
data = db.query(categories.Category).options(
joinedload(categories.Category.translations),
joinedload(categories.Category.parent)
).filter(categories.Category.parent_id.is_(None))
return data.all()
</code>
<code>@router.get("/") async def get_categories(db: Session = Depends(get_db),): data = db.query(categories.Category).options( joinedload(categories.Category.translations), joinedload(categories.Category.parent) ).filter(categories.Category.parent_id.is_(None)) return data.all() </code>
@router.get("/")
async def get_categories(db: Session = Depends(get_db),):
    data = db.query(categories.Category).options(
          joinedload(categories.Category.translations),
          joinedload(categories.Category.parent)
    ).filter(categories.Category.parent_id.is_(None))
    return data.all()

This returns me ugly response like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[
{
"created_at": "2024-07-16T09:25:24.155984+00:00",
"order": 0,
"rght": 4,
"tree_id": 1,
"level": 0,
"parent_id": null,
"updated_at": "2024-07-16T09:25:39.114618+00:00",
"id": 1,
"icon": "",
"lft": 1,
"parent": null,
"translations": [
{
"master_id": 1,
"name": "Design",
"slug": "design",
"id": 1,
"language_code": "uz"
},
{
"master_id": 1,
"name": "дизайн",
"slug": "dizain",
"id": 2,
"language_code": "ru"
}
]
}
]
</code>
<code>[ { "created_at": "2024-07-16T09:25:24.155984+00:00", "order": 0, "rght": 4, "tree_id": 1, "level": 0, "parent_id": null, "updated_at": "2024-07-16T09:25:39.114618+00:00", "id": 1, "icon": "", "lft": 1, "parent": null, "translations": [ { "master_id": 1, "name": "Design", "slug": "design", "id": 1, "language_code": "uz" }, { "master_id": 1, "name": "дизайн", "slug": "dizain", "id": 2, "language_code": "ru" } ] } ] </code>
[
  {
    "created_at": "2024-07-16T09:25:24.155984+00:00",
    "order": 0,
    "rght": 4,
    "tree_id": 1,
    "level": 0,
    "parent_id": null,
    "updated_at": "2024-07-16T09:25:39.114618+00:00",
    "id": 1,
    "icon": "",
    "lft": 1,
    "parent": null,
    "translations": [
      {
        "master_id": 1,
        "name": "Design",
        "slug": "design",
        "id": 1,
        "language_code": "uz"
      },
      {
        "master_id": 1,
        "name": "дизайн",
        "slug": "dizain",
        "id": 2,
        "language_code": "ru"
      }
    ]
  }
]

I’d like to get response only with few fields which are name, slug, order, icon, language_code, child
How can I modify my router to achieve this?

You need to create corresponding schema and use it as a response model:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class CategoryTranslationOutpuSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
slug: str
language_code: str
class CategoryOutputSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
order: int
icon: str
translations: list[CategoryTranslationOutpuSchema]
@router.get("/", response_model=list[CategoryOutputSchema])
async def get_categories(db: Session = Depends(get_db),):
data = db.query(categories.Category).options(
joinedload(categories.Category.translations),
joinedload(categories.Category.parent)
).filter(categories.Category.parent_id.is_(None))
return data.all()
</code>
<code>class CategoryTranslationOutpuSchema(BaseModel): model_config = ConfigDict(from_attributes=True) name: str slug: str language_code: str class CategoryOutputSchema(BaseModel): model_config = ConfigDict(from_attributes=True) order: int icon: str translations: list[CategoryTranslationOutpuSchema] @router.get("/", response_model=list[CategoryOutputSchema]) async def get_categories(db: Session = Depends(get_db),): data = db.query(categories.Category).options( joinedload(categories.Category.translations), joinedload(categories.Category.parent) ).filter(categories.Category.parent_id.is_(None)) return data.all() </code>
class CategoryTranslationOutpuSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    name: str
    slug: str
    language_code: str
    

class CategoryOutputSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    order: int
    icon: str
    translations: list[CategoryTranslationOutpuSchema]


@router.get("/", response_model=list[CategoryOutputSchema])
async def get_categories(db: Session = Depends(get_db),):
    data = db.query(categories.Category).options(
          joinedload(categories.Category.translations),
          joinedload(categories.Category.parent)
    ).filter(categories.Category.parent_id.is_(None))
    return data.all()

And, if you need to filter nested data, you can do it this way:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> res = [CategoryOutputSchema.model_validate(category) for category in data]
for category in res:
category.translations = [translation for translation in category.translations if translation.language_code == 'en']
return res
</code>
<code> res = [CategoryOutputSchema.model_validate(category) for category in data] for category in res: category.translations = [translation for translation in category.translations if translation.language_code == 'en'] return res </code>
    res = [CategoryOutputSchema.model_validate(category) for category in data]
    for category in res:
        category.translations = [translation for translation in category.translations if translation.language_code == 'en']

    return res

Note: FastAPI will re-validate you response. To avoid second validation you can return JSONResponse directly: https://fastapi.tiangolo.com/advanced/response-directly/

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật