2016-06-08 98 views
0

假设我有这样的模型结构:Django的迁移模型之间唯一的字段数据

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) 

我想用户配置合并到用户模式,就像这样:

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

首先,将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模型。