为什么没有插入记录?返回了一个 id,但是当我检查数据库时没有新记录。
来自 models.py
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
和views.py
DBSession.execute(text('INSERT INTO (a,b,c) VALUES (\'a\',\'b\',\'c\') RETURNING id'), params=dict(a=a,b=b,c=c))
我已经尝试使用 transaction.commit()
提交,它没有收到错误但没有插入记录。 result.fetchone()[0]
正在获取一个 id。
DBSession.commit
获取
assert self.transaction_manager.get().status == ZopeStatus.COMMITTING, "Transaction must be committed using the transaction manager"
最佳答案
这是因为您没有使用 ORM 来插入新行,因此事务不知道它应该自己提交,因为事务状态未标记为脏。
在您 DBSession.execute
views.py 中的查询之后放置以下代码。
from zope.sqlalchemy import mark_changed
session = DBSession()
session.execute(...your query...)
mark_changed(session)
此时事务应该能够正确提交您的查询,或者使用 ORM 插入新行。
这里有更多关于这个主题的内容:
https://pypi.python.org/pypi/zope.sqlalchemy/0.7.4#id15
By default, zope.sqlalchemy puts sessions in an 'active' state when they are first used. ORM write operations automatically move the session into a 'changed' state. This avoids unnecessary database commits. Sometimes it is necessary to interact with the database directly through SQL. It is not possible to guess whether such an operation is a read or a write. Therefore we must manually mark the session as changed when manual SQL statements write to the DB.
关于python - 插入不适用于 SQLAlchemy 数据库 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21058721/