python - 在 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.... 装饰器。
有人可以帮我吗?
解决方案
在数据迁移中,您应该避免直接导入模型,因为“实际”模型可能与之前的迁移不一致。
因此,例如,使用:
# 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(可能);有时,这有助于接收正确的数据库异常。
推荐阅读
- python - Python在循环中逐行读取CSV文件
- php - Symfony 表单验证在编辑中不起作用
- c# - .Net Core Web API 中使用 Identity Server 的授权
- object-detection - 如果训练数据集的图像大小小于目标检测神经网络输入图像大小会怎样?
- python - 如何在输入 numpy 数组中选择行并将操作结果存储在输出数组中的相应行中?
- javascript - 如何使用 JSPDF 将多个 base64 图像添加到 pdf 文件?
- security - 在到期时提供新的 JWT
- reactjs - 根据下拉选项过滤数据反应
- php - 使用 Altorouter 和 .htpasswd 基本身份验证
- git - 合并两个 git 分支时查找冲突文件