如何在不允许数据库中出现空值的情况下在 Django 迁移中构造“向后”函数?

How do I structure the `backwards` function in a Django migration without allowing null values in the database?

我正在实施 this answer 以将自动 UUIDField 添加到具有现有行的数据库。

建议对数据迁移进行的调整是:

from django_extensions.utils import uuid

def forwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if not item.uuid:
            item.uuid = uuid.uuid4() #creates a random GUID
            item.save()


def backwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if item.uuid:
            item.uuid = None
            item.save()

但是,我不想让 blank=True 进入我的模型。在这种情况下,我将如何调整 backwards() 功能?当前的 item.uuid = None 将不再有效...

您必须分 3 步完成迁移:

  1. UUIDField 添加到 null=True,这样现有的行就不会破坏约束。

  2. 创建数据迁移以填充类似于您当前代码的现有行的 uuid。

  3. 通过从您的字段声明中删除 null=True 添加另一个具有 NOT NULL 约束的迁移。

PS:您的代码适用于过时的南迁。当前 django-migrations 的等价物是:

def forwards(apps, schema_editor):
    MyClass = apps.get_model('myapp', 'MyClass')
    for item in MyClass.objects.all():
        # [...]