【问题标题】:Why does it throw error when I dont use List in the response_moedel?为什么我在 response_model 中不使用 List 会抛出错误?
【发布时间】:2020-11-18 16:21:05
【问题描述】:

所以我正在构建一个 fastAPI 应用程序,我希望我的响应模型从数据库中获取数据(总共 6 列)并在 API 的响应描述中返回。

@router.post("/run/new", response_model=schemas.xyzRun)
def new_request(*,
                          db: Session = Depends(get_db),
                          request: schemas.Request):

    id = service.initiate_new(db, request)
    return db.query(models.xyzRun).filter(models.xyzRun.xyzRunid == id).all()

我只是从service.initiate_new 获取 id 的值,然后从 db 中返回具有该 id 的行。 当我输入response_model=List[schemas.xyzRun] 时它可以工作,但上面的代码(没有列表)会引发错误: pydantic.error_wrappers.ValidationError:EtlRun 的 5 个验证错误

由于我迷路了,任何人都可以解释一下吗?

附加信息: models.xyzRun 是一个 xyzRun 类,我在其中给出了 __tablename____table_args__xyzRunid = Column ('xyzRunid, Integer ) 以及其他 5 个变量。

schemas.xyzRun 是一个 xyzRun 类,我在其中给出了 xyzRunid=int 和 5 个其他变量

【问题讨论】:

    标签: python fastapi pydantic uvicorn


    【解决方案1】:

    很简单,你的数据库找到了多个结果并且它在一个列表中,假设你有一个这样的模型。

    class MyModel(BaseModel):
        name: str 
        value: str 
    

    你有一个包含两列的数据库

    Name | Value
    ------------
    foo  | 1
    bar  | 2
    john | 3
    jane | 4
    

    当您向数据库发送请求并且它找到多个结果时

    响应看起来像这样:

    [{"name": "foo", "value": 1}, {"name": "bar", "value", 2}, ...]
    

    Pydantic 试图验证这一点,但它找到了一个 List 而不是 Dict 来验证,但是当你告诉它是一个列表时,它会检查该列表中的每个项目。这就是它成功返回带有List 的响应的原因。

    【讨论】:

      【解决方案2】:

      您收到错误是因为使用 filter().all() 返回 List 而不是 Dict,即它返回一组记录而不是单个记录。

      db.query(models.xyzRun).filter(models.xyzRun.xyzRunid == id).all()
      

      要获取一条记录,您应该使用

      db.query(models.xyzRun).filter(models.xyzRun.xyzRunid == id).first()
      

      如果您总是期待一条记录,您也可以使用 .one() 代替 .first()

      更多参考请查看https://docs.sqlalchemy.org/en/13/orm/tutorial.html#returning-lists-and-scalars

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 2021-12-19
        • 2023-02-04
        • 2018-07-17
        • 2017-07-08
        • 1970-01-01
        相关资源
        最近更新 更多