【问题标题】:Cannot turn off autocommit in a script using the Django ORM无法使用 Django ORM 在脚本中关闭自动提交
【发布时间】:2010-03-18 20:18:13
【问题描述】:

我有一个使用 Django ORM 和 MySQL 后端的命令行脚本。我想关闭自动提交并手动提交。对于我的生活,我无法让它发挥作用。这是脚本的精简版本。每次运行时都会在 testtable 中插入一行,并且我从 MySQL 收到此警告:“无法回滚某些非事务性更改的表”。

#!/usr/bin/python

import os
import sys

django_dir = os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(django_dir)

os.environ['DJANGO_DIR'] = django_dir
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.core.management import setup_environ
from myproject import settings

setup_environ(settings)

from django.db import transaction, connection
cursor = connection.cursor()
cursor.execute('SET autocommit = 0')
cursor.execute('insert into testtable values (\'X\')')
cursor.execute('rollback')

我还尝试将插入放在一个函数中并添加 Django 的 commit_manually 包装器,如下所示:

@transaction.commit_manually
def myfunction():
    cursor = connection.cursor()
    cursor.execute('SET autocommit = 0')
    cursor.execute('insert into westest values (\'X\')')
    cursor.execute('rollback')

myfunction()

我还尝试在 settings.py 中设置 DISABLE_TRANSACTION_MANAGEMENT = True,但没有进一步的运气。我觉得我错过了一些明显的东西。非常感谢您能给我的任何帮助。谢谢!

【问题讨论】:

    标签: python mysql django command-line


    【解决方案1】:

    您的表是 MyISAM 还是 InnoDB?请记住,MyISAM 不是事务性的,因此无法回滚。例如,请参阅 MySQL 文档中的 this page

    在事务方面,MyISAM 表实际上总是在 autocommit = 1 模式下运行。

    【讨论】:

    • 是的,我很确定 Django 默认使用 MyISAM。我知道这很明显我错过了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 2021-05-16
    • 2013-08-28
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 2021-03-03
    • 2013-07-14
    相关资源
    最近更新 更多