假设我有这种模型结构:
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)
最重要的是将现有的uuid
从UserProfile
模型迁移到新的User.uuid
(唯一)字段。应如何在django中管理> 1.7迁移?
答案 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
模型。