TransactionManagementError“在Django中进行迁移时,事务管理块以挂起的COMMIT / ROLLBACK结尾”

问题描述 投票:0回答:1

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

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

enter image description here

这是迁移文件中的代码:

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 ....装饰器。

有人可以帮我吗?

python django migration django-south
1个回答
0
投票

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

例如,使用:

# 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中;我不记得确切地该如何应付南方

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

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

从Django 1.8开始,自动提交的默认值为False(可能);有时,这有助于接收适当的数据库异常。

© www.soinside.com 2019 - 2024. All rights reserved.