Django在具有数据的模型之间迁移唯一字段

时间:2016-06-08 13:21:05

标签: python django django-models django-migrations

假设我有这种模型结构:

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迁移?

1 个答案:

答案 0 :(得分:1)

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

然后,创建一个data migration并添加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模型。