FastAPI 中未发生更新操作

问题描述 投票:0回答:2
@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
python sqlite fastapi
2个回答
0
投票

您还可以使用以下功能。首先,检索博客,然后更新其中的必填字段。我希望这能起作用

'''

@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")        

'''


-1
投票

回答

@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!"
© www.soinside.com 2019 - 2024. All rights reserved.