[英]Fetch data from 3 different tables with SQLAlchemy or SQLModel
我想用 SQLAlchemy 或 SQLModel 從 3 個表中獲取數據。 例如,假設我的表如下:
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
我想要的響應如下:
[
{
"id": 1,
"title": "This is A table",
"b": [
{
"id": 1,
"name": "This is B table",
"c":[
{
"id":1,
"text": "My text from c"
}
]
}
]
}
]
我正在嘗試使用 selectinload 但不起作用
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")
先感謝您
我已經使用較新版本的 sqlalchemy(不是 sqlmodel)嘗試了這些模型,它的工作原理如本示例所示(sqlalchemy = 1.4.39)
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
title = Column(String(length=100))
b = relationship("B", backref="a")
class B(Base):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
name = Column(String(length=100))
a_id = Column(ForeignKey('a.id', ondelete='CASCADE'))
c = relationship("C", backref="b")
class C(Base):
__tablename__ = 'c'
id = Column(Integer, primary_key=True)
text = Column(String(length=100))
b_id = Column(ForeignKey('b.id', ondelete='CASCADE'))
詢問:
stmt = select(A).options(selectinload(A.b).selectinload(B.c))
resp = await session.execute(query)
return resp.scalars().all()
(准備與此查詢相關的 pydantic model)schema.py
class CResp(BaseModel):
id: int
text: str
class BResp(BaseModel):
id: int
name: str
c: List[CResp]
class AResp(BaseModel):
id: int
title: str
b: List[BResp]
視圖.py
@app.get("/", response_model=List[AResp])
async def index(session=Depends(get_session)):
query = select(A).options(selectinload(A.b).selectinload(B.c))
resp = await session.execute(query)
return resp.scalars().all()
If you want to use this query with sqlmodel, you can try some other versions of sqlalchemy as mentioned here ( SQLModel error: "AttributeError: 'Team' object has no attribute 'heroes'" ), sqlmodel has some problems with SQLalchemy 1.4.36 + 版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.