Safe database migrations in Django

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.

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:

Step 1. 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.

Step 2. 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.

That’s all.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *