Data Migrations on Django getting previous Model versions
<p>Im working on a data migrations which needs to change a Foreign key to a different model and alter all the existing instances foreign keys to the new Model pk. I think this can be achieved with data migrations on Django. My question is:</p>

<p>Â¿How can I access previous versions of my models in order to perform the data migration?</p>

<p>I would like to do something like this:</p>

<pre><code>MyPreviousModel = previousModels.MyModel

ModelAfterMigration = afterMigrations.MyModel

all_previous = MyPreviousModel.objects.all()

for element in all_previous:
    element.previous_fk = new_foreignKey
    ModelAfterMigrations.create(element)
</code></pre>

<p>Use the versioned app registry to get the model, rather than an import statement.</p>

<pre><code>def my_migration(apps, schema_editor):
    MyModel = apps.get_model("my_app", "MyModel")
</code></pre>

<p>The first argument passed to your migration worker function is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits.</p>

python django