【发布时间】:2014-06-04 17:57:20
【问题描述】:
如何在 South 数据迁移中执行手动提交?
我创建了一个长期运行的 South 数据迁移。默认情况下,South 似乎将整个迁移包装在一个事务中。但是,由于我正在修改数百万行,如果我尝试将所有待处理的更改存储在单个事务中,这将导致数据库消耗我所有的系统内存。
为了防止这种情况,我尝试每 N 条记录调用 Django 的 commit(),但这会引发异常:
TransactionManagementError: This code isn't under transaction management
即使我用@commit_on_success 包装迁移的forwards() 方法或在forwards 的开头调用[commit_manually()][1],当我调用commit() 或South 自己的db.commit_transaction() 时仍然会出现异常。
我该如何解决这个问题?
编辑:如果我用@commit_manually 包装forwards(),这会修复错误,但是,commit() 似乎仍然没有实际提交更改。
我的代码如下:
class Migration(DataMigration):
@commit_manually
def forwards(self, orm):
mdl = orm['myapp.MyModel']
q = mdl.filter(criteria=value_to_change).only('id')
total = q.count()
i = 0
pending = []
tmp_debug = settings.DEBUG
settings.DEBUG = False
try:
for record in q.iterator():
i += 1
if i == 1 or not i % 10 or i == total:
print '\rProcessing %i of %i.' % (i, total),
sys.stdout.flush()
mdl.objects.filter(id__in=pending).update(criteria=new_value)
pending = []
# These don't seem to do anything, as the changes above aren't visible.
#commit()
db.commit_transaction()
pending.append(record.id)
finally:
settings.DEBUG = tmp_debug
我的总数大约是 300 万。在它运行时,我将从 SQL 终端查询select count(*) from myapp_mymodel where criteria=value_to_change,并且显示的计数永远不会改变。
但是,如果我将上面的代码更改为 q = q[:100] 以便它几乎立即完成,我的 SQL 查询会在迁移完成后显示更改,这意味着我的 commit() 什么都不做,真正的 commit() 只是在forwards() 完成后运行。这是什么原因造成的?
【问题讨论】:
标签: python django django-south