如何用单个SQLAlchemy查询实现按Profile ID获取订单
优化方案:单查询实现通过Profile ID获取订单详情
直接利用SQLAlchemy的联表查询或子查询,将两次数据库请求合并为一次,同时保留原逻辑的错误校验逻辑。以下是具体实现:
方案1:联表JOIN实现
@route.get("/profileId_order/{profileID}", dependencies=[Depends(check_active)], tags=["profile"]) def profileId_order(profileID: int): # 一次联表查询:关联Profile和Order表,过滤目标ProfileID result = db.query(Ordermodel)\ .join(Profilemodel, Profilemodel.profileName == Ordermodel.purchaseByName)\ .filter(Profilemodel.id == profileID)\ .all() # 验证Profile是否存在(轻量单字段查询,性能影响极小) if not db.query(Profilemodel.id).filter(Profilemodel.id == profileID).first(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Resource Not Found") # 验证是否有对应订单 if not result: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Resource Name Not Found") return result
方案2:子查询实现
@route.get("/profileId_order/{profileID}", dependencies=[Depends(check_active)], tags=["profile"]) def profileId_order(profileID: int): # 子查询获取目标Profile的名称 target_profile_name = db.query(Profilemodel.profileName)\ .filter(Profilemodel.id == profileID)\ .scalar_subquery() # 一次查询获取对应订单 result = db.query(Ordermodel)\ .filter(Ordermodel.purchaseByName == target_profile_name)\ .all() # 保留原逻辑的错误校验 if not db.query(Profilemodel.id).filter(Profilemodel.id == profileID).first(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Resource Not Found") if not result: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Resource Name Not Found") return result
关键说明
- 合并查询逻辑:通过
join()或子查询,将Profile存在性验证和订单查询的逻辑整合到一次主SQL请求中,减少数据库交互次数 - 错误提示保留:单独用轻量查询验证Profile是否存在,确保原逻辑中两种404错误提示的区分(Profile不存在/无对应订单)
- 性能优化:避免原代码的两次全表关联查询,降低数据库负载
如果不需要区分两种404错误场景,还可以进一步简化错误校验逻辑,直接根据result是否为空返回统一提示。
内容的提问来源于stack exchange,提问作者Sardar Jagpreet Singh
相关产品推荐
相关产品推荐

