Django 使用数据在模型之间迁移唯一字段

Django migrate unique field between models with data

假设我有这个模型结构:

class User(AbstractUser):
    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)


class UserProfile(models.Model):
    uuid = models.UUIDField(unique=True, null=False, default=uuid4)
    user = models.OneToOneField(User)

我想将 UserProfile 合并到 User 模型中,如下所示:

class User(AbstractUser):
    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)
    uuid = models.UUIDField(unique=True, null=False, default=uuid4)

最重要的是将现有 uuidUserProfile 模型迁移到新的 User.uuid(唯一)字段。在 django > 1.7 迁移中应该如何管理?

首先,将 uuid 字段添加到 User 模型。创建迁移。

然后,创建一个 data migration and add a RunPython 操作来调用将数据从旧模型复制到新模型的函数。类似于:

def copy_uuid(apps, schema_editor):
    User = apps.get_model("myapp", "User")

    # loop, or...
    User.objects.update(uuid=F("userprofile__uuid"))

class Migration(migrations.Migration):
    dependencies = []

    operations = [
        migrations.RunPython(copy_uuid),
    ]

迁移完成并确定一切正常后,您可以在另一个迁移中删除 UserProfile 模型。