如何在 South 数据迁移中执行手动提交?
我创建了一个长期运行的 South 数据迁移。默认情况下,South 似乎将整个迁移包装在一个事务中。但是,由于我正在修改数百万行,如果我试图在单个事务中存储所有未决更改,这将导致数据库消耗我所有的系统内存。
为了防止这种情况,我尝试每 N 条记录调用 Django 的 commit(),但这会引发异常:
TransactionManagementError: This code isn't under transaction management
即使我用 @commit_on_success 包装迁移的 forwards() 方法或在开头调用 [commit_manually()][1] forwards,当我调用 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() 仅在 forwards() 完成后运行。这是什么原因造成的?
请您参考如下方法:
您可以按 block 检索行,手动启动事务并在处理完每个 block 后提交事务。
此处描述的主要思想(已测试!):
def queryset_iterator(queryset, chunksize=1000):
pk = 0
last_pk = queryset.order_by('-pk')[0].pk
queryset = queryset.order_by('pk')
while pk < last_pk:
db.commit_transaction() # Commit the first transaction
db.start_transaction() # Start the second, committed on completion
for row in queryset.filter(pk__gt=pk)[:chunksize]:
pk = row.pk
yield row
qs = orm['myapp.MyModel'].filter(criteria=value_to_change).only('id')
for row in queryset_iterator(qs):
row.criteria=new_value
row.save()
希望这些帮助!
