首页 > 解决方案 > 历史模型在恢复 django 数据迁移时不允许删除

问题描述

我有两个模型

class A(models.Model):
    index = models.SmallIntegerField(primary_key=True)
    audio = models.FileField(null=True, blank=True)
    x = models.SmallIntegerField()
    y = models.SmallIntegerField(null=True, blank=True)

class B(models.Model):
    b = models.ForeignKey(B, on_delete=models.CASCADE)
    index = models.SmallIntegerField()
    audio = models.FileField(null=True, blank=True)
    image = models.FileField(null=True, blank=True)

我做了一个初始化模型 A 对象的数据迁移(每个对象也用它创建 B 对象,每个创建的 B 也用它创建 C 对象。)这是迁移:

from django.db import migrations


def create_as(apps, schema_editor):
    A = apps.get_model('super_app', 'A')
    B = apps.get_model('super_app', 'B')
    C = apps.get_model('super_app', 'C')  # C has FK referencing B
    # Some logic here that creates instances of A (also creates B and C)

def delete_as(apps, schema_editor):
    A = apps.get_model('super_app', 'A')
    A.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('super_app', '00xx_the_very_previous_migration'),
    ]

    operations = [
        migrations.RunPython(create_as, delete_as)
    ]

迁移成功应用了..但是当我尝试恢复迁移(应该调用delete_as)时,我总是遇到这个错误:

ValueError: Cannot query "B object (757)": Must be "B" instance.

我一直在尝试和挖掘,但不知道为什么会发生这种情况!注意:迁移中的模型类型是历史模型(__fake__.{MODEL})我尝试通过执行以下操作来使用模型的最新状态:

def delete_as(apps, schema_editor):
    A = apps.get_model('super_app', 'A')
    from django.apps import apps  # FIXME. This gives latest models state.
    B = apps.get_model('super_app', 'B')
    B.objects.all().delete()
    A.objects.all().delete()

它工作没有问题,我可以恢复迁移!但是,根据Django 文档,这不应该被使用。

关于为什么会发生这种情况的任何想法?

标签: pythondjangodjango-models

解决方案


推荐阅读