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):
class Migration(migrations.Migration):
dependencies = [
('exampleapp', 'migration_003'),
]
operations = [
migrations.CreateModel(
),
migrations.AddField(
),
migrations.RunPython(
do_data_migration
),
migrations.RemoveField(
),
]
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. , ( ).