相关疑难解决方法(0)

使用RunPython进行更改的Django迁移

我想在我的一个模型中更改一个外键,该模型当前具有NULL值,不能为空.

null=True从我的字段中删除并运行makemigrations

因为我正在改变一个已经包含该字段中包含NULL值的行的表,所以我被要求立即提供一次性值或编辑迁移文件并添加RunPython操作.

我的RunPython操作在AlterField操作之前列出,并对此字段执行所需的更新,因此它不包含NULL值(仅包含已包含NULL值的行).

但是,迁移仍然失败并出现此错误: django.db.utils.OperationalError: cannot ALTER TABLE "my_app_site" because it has pending trigger events

这是我的代码:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

def add_default_template(apps, schema_editor):
    Template = apps.get_model("my_app", "Template")
    Site = apps.get_model("my_app", "Site")

    accept_reject_template = Template.objects.get(name="Accept/Reject")
    Site.objects.filter(template=None).update(template=accept_reject_template)    

class Migration(migrations.Migration):

    dependencies = [
        ('my_app', '0021_auto_20150210_1008'),
    ]

    operations = [
        migrations.RunPython(add_default_template),
        migrations.AlterField(
            model_name='site',
            name='template',
            field=models.ForeignKey(to='my_app.Template'),
            preserve_default=False,
        ),
    ]
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,当字段被更改为不可为空但字段包含空值时,可能会发生此错误.在这种情况下,我能想到为什么会发生这种情况的唯一原因是因为RunPython操作事务在运行之前没有"提交"数据库中的更改AlterField.

如果这确实是原因 - 我如何确保更改反映在数据库中?如果不是 …

django django-migrations

20
推荐指数
2
解决办法
8300
查看次数

Django抽象模型+数据库迁移:测试抛出"不能ALTER TABLE,因为它有待处理的触发事件"

我想编写一个抽象模型mixin,我可以使用它来创建OneToOne - 与用户模型的关系.这是我的代码:

from django.conf import settings
from django.db import models


class Userable(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

    class Meta:
        abstract = True
Run Code Online (Sandbox Code Playgroud)

我为这个模型编写了以下测试:

class TestUserable(TestCase):

    mixin = Userable

    def setUp(self):
        user = User.objects.create_user(
            email="testuser@test.com",
            name="Test User",
            password="test1234test"
        )
        self.user = user
        self.model = ModelBase(
            '__TestModel__' + self.mixin.__name__, (self.mixin,),
            {'__module__': self.mixin.__module__}
        )

        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(self.model)

    def test_user(self):
        self.model.objects.create(user=self.user)
        self.assertEqual(self.model.objects.count(), 1)

    def tearDown(self):
        with connection.schema_editor() as schema_editor:
            schema_editor.delete_model(self.model)
Run Code Online (Sandbox Code Playgroud)

我的问题是,在它的tearDown()方法中的这个测试抛出了以下错误:

django.db.utils.OperationalError: cannot DROP TABLE "core___testmodel__userable" because it …
Run Code Online (Sandbox Code Playgroud)

django django-models django-testing django-tests django-migrations

8
推荐指数
1
解决办法
503
查看次数