python 尝试返回票据列表

pqwbnv8z  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(193)

新的快速API,无法找到我做错了什么
这是我的路由器-

@router.get('/{user_id}/salesbill', response_model=list[schemas.ShowSalesBill], status_code=status.HTTP_200_OK)
def get_all_salesbills(user_id: int, db: Session = Depends(get_db)):
    objs = db.query(bill_model.SalesBillModel).filter(bill_model.SalesBillModel.user_id==user_id)
    print(objs, "=================")
    return objs

这是我的模式--

class BillBase(BaseModel):
    bill_no: int
    amount: int
    about: str


class ShowSalesBill(BillBase):
    id: int
    class Config:
        orm_mode = True

这是我的模型

class SalesBillModel(Base):
    __tablename__ = "salesbill"

    id = Column(Integer, primary_key=True, index=True)
    bill_no = Column(Integer, index=True)
    amount = Column(Integer, nullable=False)
    about = Column(String(50), nullable=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete='CASCADE'))

    user = relationship("User", back_populates="salesbills")

因此,我尝试获取用户添加的所有账单,但出现错误
pydantic.错误 Package 器.验证错误:1验证错误,ShowSalesBill响应值不是有效列表(类型= type_error. list)
获取此错误

SELECT salesbill.id AS salesbill_id, salesbill.bill_no AS salesbill_bill_no, salesbill.amount AS salesbill_amount, salesbill.about AS salesbill_about, salesbill.user_id AS salesbill_user_id 
FROM salesbill 
WHERE salesbill.user_id = ? =================
INFO:     127.0.0.1:47410 - "GET /1/salesbill HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/mdhv/fastapi/env/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
e0uiprwp

e0uiprwp1#

了解错误:要放入的响应模型需要列表
架构。ShowSalesBill,而您返回的内容与预期的不同。
我建议您在BillBase中添加id

class BillBase(BaseModel):
    id : int
    bill_no: int
    amount: int
    about: str

然后创建一个迂腐模型,其中有一列包含BillBase:

class ShowSalesBill(BaseModel):
     bill_list: Optional[list[BillBase]] = []
     class Config:
         orm_mode = True

你的端点就变成这样

@router.get('/{user_id}/salesbill', response_model=schemas.ShowSalesBill, status_code=status.HTTP_200_OK)
    def get_all_salesbills(user_id: int, db: Session = Depends(get_db)):

        objs = db.query(bill_model.SalesBillModel).filter(bill_model.SalesBillModel.user_id==user_id).all()
        return schemas.ShowSalesBill(
          bill_list=[schemas.BillBase(**bill.__dict__) for bill in objs]    
)

希望能有所帮助!

相关问题