mdargacz
mdargacz

Reputation: 1379

Django migrate unique field between models with data

Let's assume I have this models structure:

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)

I would like to merge UserProfile into User model, like this:

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)

Most important thing is to migrate existing uuid from UserProfile model to new User.uuid (unique) field. How should that be managed in django > 1.7 migrations ?

Upvotes: 0

Views: 418

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48922

First, add the uuid field to the User model. Create a migration.

Then, create a data migration and add a RunPython operation to call a function that copies the data from the old to the new models. Something like:

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),
    ]

Once you've migrated and are sure that everything worked, you can delete the UserProfile model in another migration.

Upvotes: 1

Related Questions