Django Database Migrations Tip

I’ve been doing some more work with Django 3.2.9 (on Python 3.10) and I came across some sub-optimal migration strategies. I’m using PostgreSQL but this applies to any database.

I typically open and inspect auto-generated migrations to check that they are doing what I expect and to reformat the files. I have auto-format configured to run on save and use black for Python formatting.

In one of my migrations I was only adding models so I expected to see only entries for migrations.CreateModel but the migration was using a two-step process and adding a relationship later. Curiously, the model this happened to would change depending on the naming of the model, suggesting sort order was important.

I found an old ticket (makemigrations uses unnecessary AddField for ForeignKey depending on model name) showing that this used to be an issue but was fixed. Perhaps this is a regression.

Checking the generated SQL confirmed that this migration was doing more work than necessary on the database. So I manually fixed the order of the table creations in the migration so that it only used migrations.CreateModel.

The lesson here is to check that your tools are doing what you think they are doing. Plus if you auto-format all your files then the diffs are much easier to read.


Would you like help solving a technology problem in your business?
Email me for a free consultation. I'm always open to new opportunities!

This blog is treeware! If you found it useful then please plant a tree.
Donate a treeDonate a tree🌳🌳