You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI获取用户销售账单列表报错:ValidationError类型错误

问题:FastAPI返回用户销售账单列表时出现ValidationError错误

刚接触FastAPI,在实现获取指定用户所有销售账单的功能时遇到运行错误,请求路径/1/salesbill返回500内部服务器错误,控制台输出SQL查询语句后触发以下验证错误。

相关代码

路由代码

@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

Schemas代码

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


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

Model代码

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.error_wrappers.ValidationError: 1 validation error for ShowSalesBill
response
value is not a valid list (type=type_error.list)

排查与解决方法

  • 核心问题:db.query(...).filter(...)返回的是SQLAlchemy的Query对象,并非实际的账单数据列表,FastAPI无法将该对象直接序列化为list[ShowSalesBill]类型,导致验证失败。
  • 修复方案:
    在查询语句末尾添加.all()方法,执行SQL查询并获取所有结果的列表:
    objs = db.query(bill_model.SalesBillModel).filter(bill_model.SalesBillModel.user_id==user_id).all()
    
    调用.all()后,objs会变成包含SalesBillModel实例的列表,符合响应模型的类型要求,再结合ShowSalesBill中orm_mode=True的配置,Pydantic就能正确将ORM模型实例转换为响应数据。

内容的提问来源于stack exchange,提问作者mdhv_kothari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:40:55