【问题标题】:TransactionManagementError “Transaction managed block ended with pending COMMIT/ROLLBACK" while making migrations in Django在 Django 中进行迁移时,TransactionManagementError “事务管理块以挂起的 COMMIT/ROLLBACK 结束”
【发布时间】:2020-05-23 19:11:22
【问题描述】:

当我使用 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.... 装饰器。

有人可以帮帮我吗?

【问题讨论】:

  • 什么是SchemaMigration
  • 数据迁移中如何声明Organization和UserProfileRoleInOrganization?
  • @nima 这是来自 south.v2 的 South 模型,但我检查过,它继承自 BaseMigration,但几乎不是空的
  • @MarioOrlandi 如果这是您要求的,我只是做了两个“导入”声明。我知道他们工作正常
  • 我会回复一个正确的答案,以便有一些可用的格式;)

标签: python django migration django-south


【解决方案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 中是这样;我不记得具体如何与 South 相处

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

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

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

【讨论】:

  • 您好,感谢您的回答。我现在将使用正确的方法在 DataMigrations 上导入模型。我确定你告诉我的正在开发最新版本的 Django,但我测试了选项和导入,但它们都没有帮助我在 Django 1.8 上获得更好的结果。但是感谢您的帮助,现在,您将获得赏金 :)
  • 您好@Arlien,根本无意强迫您使用更新版本的 Django:我知道有时这是不可行的;)我只是想澄清一下,我的建议可能需要对 South 进行一些调整
【解决方案2】:

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

你也可以伪造迁移并重置它

【讨论】:

  • 非常感谢,我做了第一件事,但它没有用,但后来我伪造了它们,它对我有点用。我不会说解决这个问题是正确的做法,但它有助于绕过它。谢谢先生。
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 2012-04-14
  • 2016-06-23
  • 1970-01-01
  • 2022-01-09
  • 2016-10-04
  • 2016-07-07
  • 2015-10-31
相关资源
最近更新 更多