Debian Codegraph @

docs/examples/onboarding/django/dto_sqlalchemy.py

raw
1 from typing import Annotated
2
3 from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
4
5 from litestar import Litestar, post
6 from litestar.dto import DTOConfig
7 from litestar.plugins.sqlalchemy import SQLAlchemyDTO
8
9
10 class Base(DeclarativeBase):
11 pass
12
13
14 class Item(Base):
15 __tablename__ = "items"
16 id: Mapped[int] = mapped_column(primary_key=True)
17 name: Mapped[str]
18 price: Mapped[float]
19
20
21 WriteItemDTO = SQLAlchemyDTO[Annotated[Item, DTOConfig(exclude={"id"})]]
22 ReadItemDTO = SQLAlchemyDTO[Item]
23
24
25 @post("/items", dto=WriteItemDTO, return_dto=ReadItemDTO)
26 async def create_item(data: Item) -> Item:
27 data.id = 1
28 return data
29
30
31 app = Litestar(route_handlers=[create_item])