SQLAlchemy delete()函数刷新但不提交,即使调用commit()之后 [英] SQLAlchemy delete() function flushes, but does not commit, even after calling commit()

查看:107
本文介绍了SQLAlchemy delete()函数刷新但不提交,即使调用commit()之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个烧瓶应用程序,该应用程序使用 sqlalchemy 进行读取,编写 postgres 模式。当我使用 .delete()函数时,它只会刷新,但不会对数据库进行实际更改。

I have a flask app that uses sqlalchemy to read, write a postgres schema. When i use the .delete() function, it only flushes, but actual changes to the database do not occur.

Session = (sessionmaker(autocommit=False, autoflush=False,bind=conn))
sess = Session()
sess.query(Table).filter(Column.id==1).delete()
sess.commit()

我尝试了没有 scoped_session 的情况,但仍然是同样的问题。

I tried without scoped_session, but still the same issue.

推荐答案

您用被删除的行数覆盖sess,然后尝试将该数字提交到数据库。 .delete()方法返回要删除的行数( http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.delete )。

You're overwriting sess with the number of deleted rows, and then trying to commit that number to the database. The .delete() method returns the number of rows to be deleted (http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.delete).

此外,您在创建会话时将autoflush = False设置为。因此,您必须在提交后显式刷新到db。我建议这样做:

Additionally, you set autoflush=False when you created your session. That makes it so you have to explicitly flush to the db after a commit. I suggest this:

Session = sessionmaker(autocommit=False, bind=conn)
sess = Session()
rows_deleted = sess.query(Table).filter(Column.id==1).delete()
sess.commit()
print str(rows_deleted) + " rows were deleted"

这篇关于SQLAlchemy delete()函数刷新但不提交,即使调用commit()之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆