title: Is it safe to do a data migration as just one operation in a larger Django migration?
body: <p>I am handling what I assume is a common issue: I've realized that an existing model field of the model <code>Foo</code> would be better as a completely seperate model <code>Bar</code> with a foreign key to <code>Foo</code>. So, we need to make a schema migration. But what's more, since there is already existing data in the model field of <code>Foo</code>, we need to make a data migration before we delete that field.</p>
  
  <p>So we have identified that there are three distinct steps to take:</p>
  
  <ol>
  <li>Create the new table <code>Bar</code></li>
  <li>Migrate the existing data in <code>Foo</code> to the new table <code>Bar</code></li>
  <li>Delete the existing field in <code>Foo</code></li>
  </ol>
  
  <p>First, I make all the needed model changes in models.py, and then auto-generate a migration. Everything looks good, except we're going to lose all the data in the field, so I need to add one extra <a href="https://docs.djangoproject.com/en/1.8/ref/migration-operations" rel="noreferrer">operation</a> to handle the data migration (<a href="https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runpython" rel="noreferrer">RunPython)</a>. I would end up with something like the following:</p>
  
  <pre><code>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
          ),  
      ]
  </code></pre>
  
  <p>Is it safe to run a data migration as one of several operations in a migration? My worries are that there is any sort of locking going on, or if perhaps the app registry that <code>RunPython</code> passes to <code>do_data_migration</code> won't be up to date with the preceding operations?</p>
  
  <p>I am aware the I could create three migrations: one for <code>CreateModel</code> and <code>AddField</code>, the second for <code>RunPython</code>, and the last for <code>RemoveField</code>. The question is if it is functionally equivalent to do all four steps in a single migration (which provides the added benefit of making the entire migration easier to understand.)</p>