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 '<Friends at 0x35348d0>' 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()
问题解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值