How to change Django primary key from UUID to integer
After a mistake setting up the primary key of a django model to UUID a was faced with a big problem: how to change the primary key from UUID to integer in a production MySQL database with 2.5 million records?
1st approach
First i created a new field called “new_id” in my model with null=False
and editable=False
.
I already knew that migrations that add unique fields needs some extra code (as explained in the Django documentation). Then i generated the migration with python manage.py makemigrations
and modified it with the following code to create default values for rows that already exists.
After that i altered the new_id
field to be my primary key, changed its type to AutoField
and created another migration.
That approach could easily fit your needs if you have only a few thousand rows in your model’s table, like it’s the case in my development database. Unfortunately, my production database had 2.5 million rows in that single table and my server strugled a bit before i decided to stop the migration.
The solution
To get SQL code for my migration i use the command python manage.py sqlmigrate my_app 0004_my_app_new_id > migration.sql
.
Then i altered the code to generate values for the new_id
column.
It took 18 minutes to run. Finally i faked that migration and runned the next migrations.
Conclusion
Usually we change from integer primary keys to UUID primary keys. My problem was caused by a stupid mistake, therefore i recommend you to follow this tutorial only if you really know the consequences of such a major change. This is my first Medium, please consider subscribing and remember: always backup your database before messing around with SQL code.