sqlalchemy.exc.InvalidRequestError: Instance is not persisted

flask_restful 想完成从数据库中删除记录操作

文档中描述如下:

Deleting Records¶

Deleting records is very similar, instead of add() use delete():

>>> db.session.delete(me)
>>> db.session.commit()

实现代码如下

    def delete(self, id):fid = request.form['data']friend = Friends(userid=id, friendid=fid)db.session.delete(friend)db.session.commit()

报错:sqlalchemy.exc.InvalidRequestError: Instance '' is not persisted


在StackOverflow中看到:

You are trying to delete a new instance, rather than an instance you got from the database. Either you meant to use db.session.add(), or you meant to use user = User.query.filter_by(email='john@john.com').first() (or something similar) and delete that.

You might also have trouble accessing attributes of the deleted instance (assuming you delete it correctly as above). When you commit a session, all instances in that session are expired. Trying to access an expired attribute triggers a database lookup, but there can be no lookup for this object because it was deleted.

You can turn expire_on_commit off, but that is not the normal behavior and will probably cause you other problems.

You could also try calling make_transient on it.

Ultimately, you should really just abandon instances that have been deleted. There is probably a better way to do whatever you are trying to accomplish.

链接:https://stackoverflow.com/questions/26597755/invalidrequesterror-instance-user-at-0x7f65938a7510-is-not-persisted

原因是创建的friend对象在数据库中并不存在,改为:

    def delete(self, id):fid = request.form['data']# friend = Friends(userid=id, friendid=fid)friend = Friends.query.filter_by(userid=id, friendid=fid).first()db.session.delete(friend)db.session.commit()
问题解决


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部