Pablo Estrada
Pablo Estrada

Reputation: 3452

Data Migrations on Django getting previous Model versions

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:

¿How can I access previous versions of my models in order to perform the data migration?

I would like to do something like this:

MyPreviousModel = previousModels.MyModel

ModelAfterMigration = afterMigrations.MyModel

all_previous = MyPreviousModel.objects.all()

for element in all_previous:
    element.previous_fk = new_foreignKey
    ModelAfterMigrations.create(element)

Upvotes: 1

Views: 397

Answers (1)

wim
wim

Reputation: 362687

Use the versioned app registry to get the model, rather than an import statement.

def my_migration(apps, schema_editor):
    MyModel = apps.get_model("my_app", "MyModel")

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.

Upvotes: 2

Related Questions