官方文件中的示例
from django.db import connection
def my_custom_sql(self):
cursor = connection.cursor()
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
例如更新是否会影响选择
cursor.execute("UPDATE bar SET foo = foo + 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
事务是否适用于原始SQL,就像该快照代码一样有效?
from django.db import connection, transaction
def my_custom_sql(self):
try:
with transaction.atomic():
cursor = connection.cursor()
cursor.execute("UPDATE bar SET foo = foo + 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
except IntegrityError:
transaction.rollback()
还是对于第一个代码,开始游标已经开始事务?
最佳答案
我只能看到带有self.db.validate_no_broken_transaction()
here的健全性检查:
def execute(self, sql, params=None):
self.db.validate_no_broken_transaction()
self.db.set_dirty()
with self.db.wrap_database_errors:
if params is None:
return self.cursor.execute(sql)
else:
return self.cursor.execute(sql, params)
因此答案是否定的,游标默认情况下不会将原始SQL包装在事务中。
更新:
如果您需要交易和
ATOMIC_REQUESTS = False
,则可以使用decorator or context manager之类的transaction.atomic()
。注意:
django.db.connection
仅用于向后兼容。您应该使用django.db.connections['default']
甚至更好from django.db import DEFAULT_DB_ALIAS
def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided.
"""
if using is None:
using = DEFAULT_DB_ALIAS
return connections[using]
像here
关于python - Django1.6,交易适用于原始SQL吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20324660/