'FastAPI: where to set exclude_unset=True?
I am learning fastAPI and don't know how to update user info partially. The given solution is to set exclude_unset=True, but I don't know where to write it. Here are my pieces of code:
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'} works, but exclude_unset=True doesn't..
Here is my user schema:
schemas.py
class User(BaseModel):
username: str
dob: datetime.date
password: str
createdAt: datetime.datetime
Solution 1:[1]
that's because you are using it on a User model instance.
If you want to receive partial updates, it's very useful to use the parameter exclude_unset in Pydantic's model's .dict().
so use it on Pydantic object.
more info in documentation: https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict
Solution 2:[2]
Set it as follows:
a.dict(exclude_unset=True)
where a is the object, see the example here:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karol Zlot |
| Solution 2 | Keivan |
