Search code examples
djangodjango-modelsmodeldjango-migrationsmakemigrations

Django makemigrations does not create models by order in models.py


I have a question about the order in which tables are created in a migration. As there is a ForeignKey in model B to connect to model A, I create models with order of A, B and C in models.py. Then:

python manage.py makemigrations app

There is the migration file generated to create all the models, but the order is:

- Create model B
- Create model C
- Create model A
- Add field a_name to b.

As the order in models.py really matters, but why doesn't makemigrations follow the given order?


Solution

  • The order in which you place your models in your models.py matters if and only if one of them references another as a ForeignKey. In such a situation the order is important and you will find the the migration does preserve the order.

    What's really important is not what shows up when you do manage.py makemigrations but what happens when you do manage.py migrate there django usually figures out the correct order. If at anytime you feel that you want to control the order in which tables are created, you are free to edit the migration file (even though this is not really needed)