@app.put("/blog/{id}", status_code=status.HTTP_202_ACCEPTED)
def update(id, request: schemas.Blog, db: Session = Depends(get_db)):
db.query(models.Blog).filter(models.Blog.id == id).update(request)
db.commit()
return db
您还可以使用以下功能。首先,检索博客,然后更新其中的必填字段。我希望这能起作用
'''
@app.put('/blog/{id}', status_code=status.HTTP_202_ACCEPTED)
def update(id, request: schemas.Blog, db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == id).first()
if blog:
blog.title = request.title
blog.body = request.body
db.commit()
return f"Record with id {id} updated successfully!"
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Blog with id {id} is not found")
'''
回答
@app.put("/blog/{id}", status_code=status.HTTP_202_ACCEPTED)
def update(id, request: schemas.Blog, db: Session = Depends(get_db)):
db.query(models.Blog).filter(models.Blog.id == id).update(
{"title": request.title, "body": request.body}
) # **passed each field in a dict**
db.commit()
return "Record updated successfully!"