【问题标题】:FastAPI: where to set exclude_unset=True?FastAPI:在哪里设置 exclude_unset=True?
【发布时间】:2021-07-03 13:18:29
【问题描述】:

我正在学习 fastAPI,但不知道如何部分更新用户信息。给定的解决方案是设置exclude_unset=True,但我不知道在哪里写。这是我的代码:

路由器/user.py:

@router.patch('/{id}', status_code=status.HTTP_202_ACCEPTED)
def update_user(id, request: sUser, db: Session = Depends(get_db)):
    user = db.query(mUser).filter(mUser.id == id)

    if not user.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'The User with the id {id} is not found')

    user.update(request.dict(exclude={'createdAt'}, exclude_unset=True))

    db.commit()

    return user.first()

PS exclude = {'createdAt'} 有效,但 exclude_unset=True 无效..

这是我的用户架构:

schemas.py

class User(BaseModel):
    username: str
    dob: datetime.date
    password: str
    createdAt: datetime.datetime

【问题讨论】:

    标签: patch fastapi


    【解决方案1】:

    那是因为您在 User 模型实例上使用它。

    如果你想接收部分更新,在Pydantic的模型.dict()中使用参数exclude_unset非常有用。

    所以在 Pydantic 对象上使用它。

    文档中的更多信息:https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2020-03-07
      • 2016-12-25
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多