Fix Django Migration : pkey errors
Touching the same models at the same time your peers do can cause frustration on migrations. Yeah, many problems could occur, so let’s see one of the ways to deal with one of those.
It could happen when you switch between branches which touch the same models or trying to create models at the same time. Making migrations script would work fine ( python manage.py makemigrations
). But when you execute migration using python manage.py migrate
? Can’t tell… Occasionally, it will raise the pkey errors series. Somethings like:
“django_migrations _pkey” DETAIL: Key (id)=( ) already exists
It is saying that the primary key of the django_migration already exists. So the attempt to run the migration fails.
The error message could be different for different database. If you use PostgreSQL, the error message will look like
django.db.utils.IntegrityError: duplicate key value violates unique constraint “django_migrations_pkey”
DETAIL: Key (id)=(SomeNumber) already exists.
“django_migrations” is a table that Django keep historical data of what has been migrated and when.
Let’s take a look…
The picture above shows fields ofdjango_migrations
. It has applied
field which keeps the timestamp. Also, save app
and migration script name
.
Now, id
fields, which is auto-generated primary key here. The problem is the sequence
, which keep track of the latest primary key isn’t up-to-date. Let’s explain this by giving an example,
Given that django_migrations
has 20 items, the lastest one has pkey=25. But the sequence
of django_migrations
table is 22. It will cause error we mentioned above.
To fix it, I propose 2 ways.
1 ) The neat way,
Update the sequence
. You can make things right by running SQL command at the database.
This will alter sequence of django_migrations
table. You can now successfully run your migration script again.
( O v O )
2 ) The lazy way to fix it is just repeating the python manage.py migrate
. Notice that each time you run it the pkey in error message increases. The sequence
is updated every time the script fails. You rerun it until it runs successfully.
django_migrations
pkey issue fixed, you might get more errors from django_content_type
and auth_permission
tables.
When you add a new model to the apps, Django keeps track of all available models incontent_type
tables. And also store its auth_permission
accordingly. You can just apply the same technique to fix the sequence
here.
django.db.utils.IntegrityError: duplicate key value violates unique constraint “django_content_type_pkey”
DETAIL: Key (id)=( ) already exists.django.db.utils.IntegrityError: duplicate key value violates unique constraint “auth_permission_pkey”
DETAIL: Key (id)=( ) already exists