Skip to content

Instantly share code, notes, and snippets.

@smcoll
Created August 7, 2018 15:30
Show Gist options
  • Select an option

  • Save smcoll/b2580c0cb7cb390c7f54d7eb8cab6ce0 to your computer and use it in GitHub Desktop.

Select an option

Save smcoll/b2580c0cb7cb390c7f54d7eb8cab6ce0 to your computer and use it in GitHub Desktop.

Revisions

  1. smcoll created this gist Aug 7, 2018.
    41 changes: 41 additions & 0 deletions 0002_merge_tables.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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
    ]