Mahdi
Mahdi

Reputation: 35

Issue with Django data migration when model changes later

Let's say I have a Django model that looks like this:

class MyEntity(models.Model):
    my_first_attribute = models.CharField(max_length=50)

I create a data migration that inserts some values in MyEntity model.

Then I create a schema migration that adds another attribute "my_second_attribute".

If I run ./migrate.py on a fresh database, running the data migration fails and Django complains that myentity.my_second_attribute doesn't exist!

Is there a solution for this?

Upvotes: 1

Views: 252

Answers (1)

Piotr Ćwiek
Piotr Ćwiek

Reputation: 1650

Be sure that your data migration function does this:

Person = apps.get_model("yourappname", "Person")

Rather than using this:

from yourappname.models import Person

The former will assume database schema and models as defined by previous schema migration(s) (as specified in Migration.dependencies).

The latter will use current sources which may go way ahead of the state known to migration files.

Upvotes: 4

Related Questions