Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order in django migrations

we are working on a web application that has one central app, and a new one we added lastly.

The migrations order is the following:

contenttypes 0001 
contenttypes 0002

auth         0001
...
auth         0006

main_app     0001
...
main_app     0045

After adding the new app, the migration's order was the following:

contenttypes 0001
auth         0001
main_app     0001
...
main_app     0045
contenttypes 0002
auth         0002
...
auth         0006
new_app      0001

There are few things worth to note:

  1. new_app.0001 migration has the dependencies (in this order):

    auth.0006
    main_app.0045
    

    And only create a foreign key to user.

  2. auth.0004 migration update the username to have a max length of 30

  3. my_app.0012 udpate the user.username field to have a length of 255 (through some AlterField-derived class)

So because of the order in which the migration are ran, without the new_app, the resulting user.username length is 30 instead of 255.

In the initial my_app migration, we have the following dependency:

migrations.swappable_dependency(settings.AUTH_USER_MODEL)

(which seems to be required when you change the default django user model).

The questions are: Why is the order of the migration changes ? How to prevent it ?

Note: we did found a "hacky" way to prevent this, by adding a dependency in the my_app initial migration:

migrations.swappable_dependency(settings.AUTH_USER_MODEL),
auth.0006

But we do not think this is a viable solution, so we are looking for a better one.

like image 590
nobe4 Avatar asked Apr 11 '16 08:04

nobe4


1 Answers

Django tries to create a consistent migration order by first ordering all dependencies in a single migration in alphabetical order, and then using a depth-first search to create the final migration plan. Since the migration plan is always resolved at runtime, a single change may occasionally have a big impact on the final migration plan.

If you need one migration to run after another, adding a dependency is the correct solution. Migrations are designed so that you can write them yourself if the auto-generated migrations don't suit your needs. How to control the order of migrations is covered by the docs.

like image 112
knbk Avatar answered Oct 05 '22 12:10

knbk