Is it safe to migrate data as a single operation with more Django migration?

I do what I think is a common problem: I realized that the existing model model field Foowould be better than a completely separate model Barwith a foreign key Foo. So, we need to migrate the schema. But what else, since Foothere is already data in the model field , we need to migrate the data before we delete this field.

So, we have determined that there are three different steps:

  • Create a new table Bar
  • Move existing data to Fooa new tableBar
  • Delete existing field in Foo

First, I make all the necessary changes to the model in models.py, and then automatically generate the migration. Everything looks good, except that we will lose all the data in the field, so I need to add one additional operation to handle data migration ( RunPython) . I get the following:

def do_data_migration(apps, schema_editor):
    # Migrate data from Foo to Bar

class Migration(migrations.Migration):

    dependencies = [ 
        ('exampleapp', 'migration_003'),
    ]   

    operations = [ 
        migrations.CreateModel(
            # Create the new model Bar
        ),  
        migrations.AddField(
            # Add the foreign key field to model Foo
        ),  
        migrations.RunPython(
            do_data_migration
        ),
        migrations.RemoveField(
            # Remove the old field from Foo
        ),  
    ]

Is it safe to perform data migration as one of several migration operations? Am I worried that some kind of blockage is occurring, or maybe the application registry that RunPythongoes to do_data_migrationwill not be updated with previous operations?

, : CreateModel AddField, RunPython RemoveField. , ( ).

+4
1

Django, . . RunPython , Bar Foo.

, . DDL (Data Definition Language) , Django . PostgreSQL, , DDL , . / .

MySQL Oracle, DDL RunPython , . .

+3

All Articles