Safe Django database migrations


What's inside this article ⌄
  • Django safe migration practices
  • How to migrate Django safely
  • Django database migration guide
  • Zero downtime Django migrations

The simple process of renaming a DB column becomes more complex when DB migrations in specific scenarios are applied before code updates by pipeline.

It means that there may be a timeframe, when the “old” code will be running against the “new” database schema.

Therefore, using the built-in Django rename functionality will lead to errors. “Old” Django code tries to execute a query that contains an old column, but there is no such column in the DB, and it gives a SQL error even if this field is marked as optional on the Django side.

The solution here is to separate this rename thing into two steps.


First step

Remove column from all Python code and from the Django model itself. DO NOT execute the make migrations command. Supply this code to all stages, carefully ensuring that all things work well.

Second step

Add a column with the new name to the model. Execute make migrations. Django will ask you whether you want this type of operation to be just “rename” or “remove an old column and add a new column”.

I believe you should answer this question considering the existing data that resides in DB for this column. Supply this code to all stages, carefully ensuring that all things work well.