Created
August 7, 2018 15:30
-
-
Save smcoll/b2580c0cb7cb390c7f54d7eb8cab6ce0 to your computer and use it in GitHub Desktop.
Django migration to merge one table's records into another similar table (both having UUID primary keys)
This file contains hidden or 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
from django.db import migrations | |
def merge_foo_into_bar(apps, schema_editor): | |
""" For each FooCategory, create a corresponding BarCategory (with the new type) | |
and for each Foo, create a corresponding Bar. | |
The idea is that Foo and FooCategory would be dropped in a subsequent migration. | |
""" | |
Foo = apps.get_model('myapp', 'Foo') | |
FooCategory = apps.get_model('myapp', 'FooCategory') | |
Bar = apps.get_model('myapp', 'Bar') | |
BarCategory = apps.get_model('myapp', 'BarCategory') | |
BarCategory.objects.bulk_create([ | |
BarCategory( | |
id=obj.id, # since the ID is a UUID, this should be ok | |
title=obj.name, | |
# ...maybe additional attributes set here | |
) for obj in FooCategory.objects.all() | |
]) | |
Bar.objects.bulk_create([ | |
Bar( | |
id=obj.id, | |
internal_name=obj.internal_name, # FIXME: if this column is unique, there could be collision | |
category_id=obj.category_id, # since the FooCategory.id was preserved | |
text=obj.text | |
) for obj in Foo.objects.all() | |
]) | |
class Migration(migrations.Migration): | |
dependencies = [ | |
('myapp', '0001_initial'), | |
] | |
operations = [ | |
migrations.RunPython(merge_foo_into_bar) # not reversible | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment