I want to fetch data from 3 tables with SQLAlchemy or SQLModel. For example lets say that my tables are the following:
class A(SQLModel, table=true):
id: int
title: str
class B(SQLModel, table=true):
id: int
a_id: foreign_key("a.id")
name: str
class C(SQLModel, table=true):
id: int
b_id: foreign_key("b.id")
text: str
The response that I want to have is the following:
[
{
"id": 1,
"title": "This is A table",
"b": [
{
"id": 1,
"name": "This is B table",
"c":[
{
"id":1,
"text": "My text from c"
}
]
}
]
}
]
I am trying with selectinload but doesn't work
query = (
select(A)
.where(A.id == a_id)
.options(
selectinload(A.b).joinedload(
B.c
)
)
)
try:
response = (await session.exec(query)).one()
except NoResultFound:
raise HTTPException(status_code=404, detail="Data not found")
Thank you in advance