Django中的游标是否在打开的事务中运行? [英] Do cursors in Django run inside the open transaction?
问题描述
我的Django应用程序正在使用一些自定义SQL,该SQL在如下视图中执行:
My Django application is using some custom SQL which I am executing inside a view like this:
db = router.db_for_write(model)
cursor = connections[db].cursor()
cursor.execute("INSERT INTO ....")
由于我使用的是 TransactionMiddleware
,因此我的视图正在事务内运行,但是我不清楚是否能获得像这样的新游标会转义当前打开的事务,或者如果该游标仍是打开事务的一部分。我收到一些错误消息,使我相信游标正在事务中运行。
Since I am using the TransactionMiddleware
, my view is running inside a transaction, but I'm not clear if getting a new cursor like this "escapes" the currently open transaction or if the cursor is still a part of the open transaction. I am getting some error messages that lead me to believe that cursor is running inside the transaction.
我希望能够使用游标在 TransactionMiddleware $ c $打开的事务之外执行SQL命令。 c>。
I would like to be able to use a cursor to execute SQL commands outside of the transaction that was opened by the TransactionMiddleware
. Is this possible?
如果重要的话,我正在PostgreSQL 8.4数据库上运行Django 1.4。
If it matters, I am running Django 1.4 with a PostgreSQL 8.4 database.
推荐答案
如果有一个要手动管理事务的视图,则应在该视图中使用装饰器手动提交。
If there is a view in which you want to manage the transaction manually, you should use the decorator in that view to commit_manually.
来自文档。
from django.db import transaction
@transaction.commit_manually
def viewfunc(request):
...
# You can commit/rollback however and whenever you want
transaction.commit()
...
# But you've got to remember to do it yourself!
try:
...
except:
transaction.rollback()
else:
transaction.commit()
@transaction.commit_manually(using="my_other_database")
def viewfunc2(request):
....
是的,导入事务游标仅提供事务的游标,而不会创建新的事务。
And yes, importing a transaction cursor only provides the the cursor of the transaction, and does not create a new transaction.
这篇关于Django中的游标是否在打开的事务中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!