[Fixed]-Django migrate unique field between models with data

1👍

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.

Leave a comment