FastAPI:在哪里设置exclude_unset=True



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

routers/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

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

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

所以在Pydantic对象上使用它。

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

设置如下:

a.dict(exclude_unset=True)

其中a是对象,请参见此处的示例:

https://github.com/samuelcolvin/pydantic/issues/1399

最新更新