在SQLAlchemy中使用一个查询检索数据



给定配置文件ID获取订单

@route.get("/profileId_order/{profileID}", dependencies=[Depends(check_active)], tags=["profile"])
def profileId_order(profileID: int):
profile = db.query(Profilemodel).filter(Profilemodel.id==profileID).first()
# if given profile_id is not exist it will raise error else return profile.
if profile is None:       
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Resource Not Found")
result = db.query(Ordermodel).filter(profile.profileName==Ordermodel.purchaseByName).all()
# if given name is not matched it will raise error else return profile.
if result is None:       
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Resource Name Not Found")
return result

在上面的代码中,我从带有profileId(配置文件表)的订单表中获取订单详细信息,代码中有两个查询用于检索数据。


如何用一个查询检索数据?

的例子:

给定产品名称,获取购买该产品的所有配置文件

python

@route.get("/product_name/{product_name}", dependencies=[Depends(check_admin)], tags=["order"])
def get_productName_profile(product_name:str):
result = []
for c, i in db.query(Ordermodel.purchaseByName,Profilemodel).filter(Ordermodel.purchaseByName==Profilemodel.profileName and product_name==Ordermodel.productName).all():
result.append(i)
#pro = db.query(Profilemodel.profileName).all()
return result

我想你正在寻找连接函数。这可以通过原始SQL查询或sqlalchemy API实现。

的例子:

result = list(db.query(Ordermodel).join(Profilemodel, Profilemodel.profileName == Ordermodel.purchaseByName).filter(Profilemodel.id==profileID).all())

但是,我看到您希望首先检查配置文件是否存在,并在没有此ID的情况下返回404响应。在这种情况下,如果您仍然希望返回错误,则不能避免这两个查询。

最新更新