Debian Codegraph @

docs/examples/data_transfer_objects/factory/related_items.py

raw
1 from __future__ import annotations
2
3 from uuid import UUID
4
5 from sqlalchemy import ForeignKey
6 from sqlalchemy.orm import Mapped, mapped_column, relationship
7 from typing_extensions import Annotated
8
9 from litestar import Litestar, put
10 from litestar.dto import DTOConfig
11 from litestar.plugins.sqlalchemy import SQLAlchemyDTO
12
13 from .my_lib import Base
14
15
16 class A(Base):
17 b_id: Mapped[UUID] = mapped_column(ForeignKey("b.id"))
18 b: Mapped[B] = relationship(back_populates="a")
19
20
21 class B(Base):
22 a: Mapped[A] = relationship(back_populates="b")
23
24
25 data_config = DTOConfig(max_nested_depth=0)
26 DataDTO = SQLAlchemyDTO[Annotated[A, data_config]]
27
28 # default config sets max_nested_depth to 1
29 ReturnDTO = SQLAlchemyDTO[A]
30
31
32 @put("/a", dto=DataDTO, return_dto=ReturnDTO, sync_to_thread=False)
33 def update_a(data: A) -> A:
34 # this shows that "b" was not parsed out of the inbound data
35 assert "b" not in vars(data)
36 # Now we'll create an instance of B and assign it"
37 # This includes a reference back to ``a`` which is not serialized in the return data
38 # because default ``max_nested_depth`` is set to 1
39 data.b = B(id=data.b_id, a=data)
40 return data
41
42
43 app = Litestar(route_handlers=[update_a])
44
45 # run: /a -H "Content-Type: application/json" -X PUT -d '{"id": "6955e63c-c2bc-4707-8fa4-2144d1764746", "b_id": "9cf3518d-7e19-4215-9ec2-e056cac55bf7", "b": {"id": "9cf3518d-7e19-4215-9ec2-e056cac55bf7"}}'