Accessing M2M models in the handler #4076
Unanswered
Daniel-Sedlacek
asked this question in
Q&A
Replies: 1 comment 3 replies
-
@Daniel-Sedlacek PiccoloDTO cannot handle nested data, but luckily Piccolo has an output method that can handle deeply nested data and you can use that. You can use a import typing as t
from pydantic import BaseModel, UUID4
class ServiceModelIn(BaseModel):
name: str
appointments: t.List[UUID4]
class ServiceModelOut(BaseModel):
id: UUID4
name: str
class AppointmentModelIn(BaseModel):
customer_name: str
services: t.List[UUID4]
class AppointmentModelOut(BaseModel):
id: UUID4
customer_name: str
services: t.List[ServiceModelOut]
@get("/appointments", tags=["Appointment"])
async def appointments() -> t.List[AppointmentModelOut]:
results = (
await Appointment.select(
Appointment.all_columns(),
Appointment.services(),
)
.order_by(Appointment._meta.primary_key, ascending=False)
.output(nested=True)
)
# print([AppointmentModelOut(**result) for result in results])
#[
# AppointmentModelOut(
# id=UUID("c67439d0-d1e0-4061-98f3-d40068157f0a"),
# customer_name="John Doe",
# services=[
# ServiceModelOut(
# id=UUID("c2ed749b-345c-4bdd-8dd3-2f65ddd472f3"), name="Haircut"
# )
# ],
# )
# ]
return [AppointmentModelOut(**result) for result in results] Use the same code if you want to return a nested response from the post method. If you need an example of the post method, I can provide it in future comments. Hope this helps. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone, first of all I want to give a big thumbs up for Litestar, it's a great project and I'm truly happy to be able to use it.
However, I got into this problem that I can't solve.
The Problem
I'm struggling with retrieving nested data from many-to-many relationship model in a route handler. Specifically, I need to handle nested service data when creating appointments.
Code Example
Here's my model structure that uses the M2M implementation according to Piccolo's docs:
When I send this JSON payload from the frontend:
My current DTOs look like this:
And the route handler:
Question
How can I properly parse this nested data structure using DTOs and then retrieve the whole Appointment model, including the nested Service data? The data.create_instance() doesn't include the nested service data in this case.
What I expect to get from data.create_instance():
but what I actually get:
Any help would be greatly appreciated! 🙏
Beta Was this translation helpful? Give feedback.
All reactions