插入不适用于SQLAlchemy数据库会话

2024-04-25 06:52:04 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么不插入记录?返回了一个id,但是当我检查数据库时没有新的记录。在

来自模型.py

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

而且视图.py

^{pr2}$

我尝试过用transaction.commit()提交,它没有错误,但没有插入记录。result.fetchone()[0]正在获取id

DBSession.commit它得到

assert self.transaction_manager.get().status == ZopeStatus.COMMITTING, "Transaction must be committed using the transaction manager"

Tags: frompy模型importid数据库zopesqlalchemy
2条回答

试试看

DBSession.flush()

执行后

这是因为您没有使用ORM插入新行,因为refore事务不知道它应该自己提交,因为事务状态没有标记为dirty。在

将以下代码放在DBSession.execute中的查询之后视图.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.

相关问题 更多 >