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

TransactionManagementError “Transaction managed block ended with pending COMMIT/ROLLBACK" while making migrations in Django

提问人:Arlien 提问时间:2/8/2020 最后编辑:CommunityArlien 更新时间:2/18/2020 访问量:341

问:

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

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 迁移 django-south

评论

0赞 nima 2/11/2020
什么?SchemaMigration
0赞 Mario Orlandi 2/12/2020
您是如何在数据迁移中声明 Organization 和 UserProfileRoleInOrganization 的?
0赞 Arlien 2/12/2020
@nima 这是来自 south.v2 的南方模型,但我检查了一下,它继承自 BaseMigration,但几乎不为空
0赞 Arlien 2/12/2020
@MarioOrlandi我只是做了两个“进口”声明,如果这是你所要求的。我知道他们工作正常
0赞 Mario Orlandi 2/12/2020
我会回复一个正确的答案,以便;)提供一些格式

答:

1赞 Mario Orlandi 2/12/2020 #1

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

因此,例如,使用:

# 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(可能);有时,这有助于接收正确的数据库异常。

评论

0赞 Arlien 2/12/2020
您好,感谢您的回答。我现在将使用正确的方法在 DataMigrations 上导入模型。我敢肯定你告诉我的是在最新版本的 Django 上工作的,但我测试了选项和导入,它们都没有帮助我在 Django 1.8 上获得更好的结果。但是感谢您的帮助,现在,您将获得赏金:)
0赞 Mario Orlandi 2/12/2020
你好@Arlien,无意强迫你使用较新版本的 Django:我知道有时这是不可行的;)我只是想澄清一下,我的建议可能需要对南方进行一些调整
1赞 Suhas Kashyap 2/18/2020 #2

删除迁移文件夹并重新运行迁移 ./manage.py MakeMigrations 应用程序 ./manage.py 迁移

您还可以伪造迁移并重置它

评论

0赞 Arlien 2/18/2020
非常感谢,我做了第一件事,但没有用,但后来我伪造了它们,它对我有用。我不会说解决这个问题是正确的做法,但它有助于绕过它。谢谢你,先生。