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='[email protected]').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()
问题解决

你可能感兴趣的:(#,Flask)