Sqlalchemy + FastAPI. Return ORM model result with nested childs

I have table “categories” with subcategories. Subcategories are determined by “parent_id”.

I want to find a way to return an object from FastAPI’s endpoint like this:

[
  {
    "name": "Category",
    "id": "599a5906-1ba1-45ca-9af9-bac2e1513519",
    "created_at": "2024-07-17T21:25:24.590781",
    "child": [
      {
        "name": "SubCategory",
        "id": "bc540161-e390-4982-87a8-f8eff47204b6",
        "created_at": "2024-07-17T21:25:43.307017",
        "child": null
      }
    ]
  }
]

SQlAlchemy model (here I created a relationship as adviced in this question):

from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from database._types import created_at, uuid, uuidpk
from database.engine import Base


class CategoriesModel(Base):
    __tablename__ = "categories"

    id: Mapped[uuidpk]
    parent_id: Mapped[uuid | None] = mapped_column(ForeignKey("categories.id"))
    name: Mapped[str]
    created_at: Mapped[created_at]

    child: Mapped[list["CategoriesModel"]] = relationship(
        "CategoriesModel",
        remote_side=[parent_id],
        uselist=True
    )

Query method from repository:

class SQLAlchemyRepository[T]:
    def __init__(self, session: AsyncSession) -> None:
        self._model: MappedClassProtocol = get_args(self.__orig_bases__[0])[0]
        self._session = session


class CategoriesRepository(SQLAlchemyRepository[CategoriesModel]):
    async def get_many(self) -> list[Row]:
        stmt = (
            select(self._model.id, self._model.name, self._model.created_at)
            .order_by(self._model.name)
        )
        res = await self._session.execute(stmt)
        return res.all()

Pydantic models:

from datetime import datetime
from _types import uuid


class SQLAlchemyMappedModel(BaseModel):
    class Config:
        from_attributes = True


class CategorySchema(SQLAlchemyMappedModel):
    name: str


class CategoryOut(CategorySchema):
    id: uuid
    created_at: datetime
    child: list["CategorySchema"] = []

Endpoint:

@router.get("/", summary="Categories")
async def get_categories(
    uow: Annotated[IUnitOfWork, Depends(get_uow)],
) -> list[CategoryOut]:
    async with uow:
        res = await uow.categories.get_many()
        await uow.commit()
    return res

SQLAlchemy doesn’t return “child”. So the result is different from expected.

[
  {
    "name": "Category",
    "id": "599a5906-1ba1-45ca-9af9-bac2e1513519",
    "created_at": "2024-07-17T21:25:24.590781",
    "child": []
  },
  {
    "name": "SubCategory",
    "id": "bc540161-e390-4982-87a8-f8eff47204b6",
    "created_at": "2024-07-17T21:25:43.307017",
    "child": []
  }
]

I’ve decided not to include code unrelated to the question (FastAPI dependencies, UOW), but if a minimally reproducible example is needed, I can do that.

The problem was in the incorrect query. It should be like this:

from sqlalchemy.orm import joinedload


class CategoriesRepository(SQLAlchemyRepository[CategoriesModel]):
    async def get_many(self) -> list[Row]:
        stmt = (
            select(self._model)
            .options(joinedload(self._model.child))
            .order_by(self._model.name)
        )
        res = await self._session.execute(stmt)
        return res.unique().scalars().all()

In this way ORM generate a correct SQL query (print(stmt)):

SELECT categories.id, categories.parent_id, categories.name, categories.created_at, categories_1.id AS id_1, categories_1.parent_id AS parent_id_1, categories_1.name AS name_1, categories_1.created_at AS created_at_1
    FROM categories
    LEFT OUTER JOIN categories AS categories_1
        ON categories.id = categories_1.parent_id
ORDER BY categories.name

Some examples about sync usage cases could be found in the official docs. But I couldn’t find any about asynchronous use.

Also I made a mistake in pydantic model:

class CategoryOut(CategorySchema):
    id: uuid
    created_at: datetime
    child: list["CategorySchema"] = []

child field should be annotated by its class:
child: list["CategoryOut"] = []

3

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

Sqlalchemy + FastAPI. Return ORM model result with nested childs

I have table “categories” with subcategories. Subcategories are determined by “parent_id”.

I want to find a way to return an object from FastAPI’s endpoint like this:

[
  {
    "name": "Category",
    "id": "599a5906-1ba1-45ca-9af9-bac2e1513519",
    "created_at": "2024-07-17T21:25:24.590781",
    "child": [
      {
        "name": "SubCategory",
        "id": "bc540161-e390-4982-87a8-f8eff47204b6",
        "created_at": "2024-07-17T21:25:43.307017",
        "child": null
      }
    ]
  }
]

SQlAlchemy model (here I created a relationship as adviced in this question):

from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from database._types import created_at, uuid, uuidpk
from database.engine import Base


class CategoriesModel(Base):
    __tablename__ = "categories"

    id: Mapped[uuidpk]
    parent_id: Mapped[uuid | None] = mapped_column(ForeignKey("categories.id"))
    name: Mapped[str]
    created_at: Mapped[created_at]

    child: Mapped[list["CategoriesModel"]] = relationship(
        "CategoriesModel",
        remote_side=[parent_id],
        uselist=True
    )

Query method from repository:

class SQLAlchemyRepository[T]:
    def __init__(self, session: AsyncSession) -> None:
        self._model: MappedClassProtocol = get_args(self.__orig_bases__[0])[0]
        self._session = session


class CategoriesRepository(SQLAlchemyRepository[CategoriesModel]):
    async def get_many(self) -> list[Row]:
        stmt = (
            select(self._model.id, self._model.name, self._model.created_at)
            .order_by(self._model.name)
        )
        res = await self._session.execute(stmt)
        return res.all()

Pydantic models:

from datetime import datetime
from _types import uuid


class SQLAlchemyMappedModel(BaseModel):
    class Config:
        from_attributes = True


class CategorySchema(SQLAlchemyMappedModel):
    name: str


class CategoryOut(CategorySchema):
    id: uuid
    created_at: datetime
    child: list["CategorySchema"] = []

Endpoint:

@router.get("/", summary="Categories")
async def get_categories(
    uow: Annotated[IUnitOfWork, Depends(get_uow)],
) -> list[CategoryOut]:
    async with uow:
        res = await uow.categories.get_many()
        await uow.commit()
    return res

SQLAlchemy doesn’t return “child”. So the result is different from expected.

[
  {
    "name": "Category",
    "id": "599a5906-1ba1-45ca-9af9-bac2e1513519",
    "created_at": "2024-07-17T21:25:24.590781",
    "child": []
  },
  {
    "name": "SubCategory",
    "id": "bc540161-e390-4982-87a8-f8eff47204b6",
    "created_at": "2024-07-17T21:25:43.307017",
    "child": []
  }
]

I’ve decided not to include code unrelated to the question (FastAPI dependencies, UOW), but if a minimally reproducible example is needed, I can do that.

The problem was in the incorrect query. It should be like this:

from sqlalchemy.orm import joinedload


class CategoriesRepository(SQLAlchemyRepository[CategoriesModel]):
    async def get_many(self) -> list[Row]:
        stmt = (
            select(self._model)
            .options(joinedload(self._model.child))
            .order_by(self._model.name)
        )
        res = await self._session.execute(stmt)
        return res.unique().scalars().all()

In this way ORM generate a correct SQL query (print(stmt)):

SELECT categories.id, categories.parent_id, categories.name, categories.created_at, categories_1.id AS id_1, categories_1.parent_id AS parent_id_1, categories_1.name AS name_1, categories_1.created_at AS created_at_1
    FROM categories
    LEFT OUTER JOIN categories AS categories_1
        ON categories.id = categories_1.parent_id
ORDER BY categories.name

Some examples about sync usage cases could be found in the official docs. But I couldn’t find any about asynchronous use.

Also I made a mistake in pydantic model:

class CategoryOut(CategorySchema):
    id: uuid
    created_at: datetime
    child: list["CategorySchema"] = []

child field should be annotated by its class:
child: list["CategoryOut"] = []

3

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