【问题标题】:Django migrate unique field between models with dataDjango在具有数据的模型之间迁移唯一字段
【发布时间】:2016-10-08 19:03:46
【问题描述】:

假设我有这个模型结构:

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 迁移中应该如何管理?

【问题讨论】:

    标签: python django django-models django-migrations


    【解决方案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 模型。

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2012-05-19
      • 1970-01-01
      • 2015-03-06
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      相关资源
      最近更新 更多