首页 > 解决方案 > 在 Django 中进行迁移时,TransactionManagementError “事务管理块以挂起的 COMMIT/ROLLBACK 结束”

问题描述

当我使用python manage.py migrate manage (是的,它是 Django 1.8 并且我无法更改它:/)进行迁移时,迁移(我测试的每一个)总是失败并出现相同的错误:

django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

在此处输入图像描述

这是迁移文件中的代码:

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Check expiry keys in Organization
        for org in Organization.objects.all():
            self.checkExpiryDate(org)
        # Check expiry keys in UserProfileRoleInOrganization
        for uprio in UserProfileRoleInOrganization.objects.all():
            self.checkExpiryDate(uprio)

    def checkExpiryDate(self, entity):
        # Check if expiry_date is consistent with apikey and fix it if necessary
        if not entity.date_has_changed:
            return
        date_in_key = entity.getExpiryDateInKey()
        if not date_in_key:
            return
        y = int(date_in_key[:4])
        m = int(date_in_key[4:-2])
        d = int(date_in_key[-2:])
        entity.expiry_date = datetime.datetime(y,m,d)
        entity.save()

    def backwards(self, orm):
        pass

我已经看到了其他类似问题的一些答案,但不,我的代码中没有任何 @commit.... 装饰器。

有人可以帮我吗?

标签: pythondjangomigrationdjango-south

解决方案


在数据迁移中,您应该避免直接导入模型,因为“实际”模型可能与之前的迁移不一致。

因此,例如,使用:

# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model('yourappname', 'Person')

代替

from yourappname.models import Person

请参阅:https ://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations

至少在最新版本的 Django 中是这样;我不记得具体如何与 South 相处

您也可以尝试将此选项添加到 DATABASES['default'] 定义中:

'OPTIONS': {'autocommit': True,}

因为对于 Django 1.8,自动提交的默认值是 False(可能);有时,这有助于接收正确的数据库异常。


推荐阅读