Last active
August 6, 2024 20:14
-
-
Save smcoll/8bb867dc631433c01fd0 to your computer and use it in GitHub Desktop.
Django migration converting integer pk table to UUID pk table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import unicode_literals | |
import uuid | |
from django.db import migrations, models | |
def fill_mymodel_uuid(apps, schema_editor): | |
db_alias = schema_editor.connection.alias | |
MyModel = apps.get_model('myapp', 'MyModel') | |
for obj in MyModel.objects.using(db_alias).all(): | |
obj.uuid = uuid.uuid4() | |
obj.save() | |
class Migration(migrations.Migration): | |
""" Change model with integer pk to UUID pk. This migration presumes there | |
are no db constraints (foreign keys) to this table. | |
""" | |
dependencies = [ | |
# ... | |
] | |
operations = [ | |
migrations.AddField( | |
model_name='mymodel', | |
name='uuid', | |
field=models.UUIDField(null=True), | |
), | |
migrations.RunPython(fill_mymodel_uuid, migrations.RunPython.noop), | |
migrations.AlterField( | |
model_name='mymodel', | |
name='uuid', | |
field=models.UUIDField(default=uuid.uuid4, serialize=False, editable=False, unique=True), | |
), | |
migrations.RemoveField('MyModel', 'id'), | |
migrations.RenameField( | |
model_name='mymodel', | |
old_name='uuid', | |
new_name='id' | |
), | |
migrations.AlterField( | |
model_name='mymodel', | |
name='id', | |
field=models.UUIDField(primary_key=True, default=uuid.uuid4, serialize=False, editable=False), | |
), | |
] |
@smcoll @gabn88 I have uploaded code, which ensures that the foreign key relations are maintained. Please check it out here: https://github.com/sharshub/django-pk-to-uuid.
@smcoll, thanks for this, it helped with my migrations. I used this to build upon and implement my code.
@sharshub Thanks für this really good help!
Have you or (anyone else here) done it for many2many relations as well? I have no idea how to change the id's in the intermediate tables.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gabn88 that's trickier. Off the top of my head, i think you have to do something like this, with each step as its own migration file:
to_field
), and make it notnull (adding the constraint)Notice that i left out the last two operations... if you want an
id
column and correspondingfoo_id
columns on the related tables (rather thanuuid
andfoo_uuid
columns), then i think you have to drop the foreign key constraints altogether, do the column renaming, and then add the constraints back afterward.Please someone correct me if i'm wrong there.