[Solved] Keep getting `IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(n) already exists.`

Hi everyone,

I’ve encountered an issue that has left me scratching my head and I’m hoping someone here might be able to point me in the right direction.

After installing django-simple-history, I attempted to migrate my database and was met with the following error: IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(11) already exists.

This situation is identical to the one described in this StackOverflow thread. Following the advice of the top-voted answer, I checked the last value from django_migrations_id_seq and found it to be 51.

However, once I dropped the tables created by the previous migrate command and ran migrate again, I found myself back in the same situation. The Key (id)=(11) keeps incrementing with each attempt.

I’m afraid my understanding of both databases and Django falls short when it comes to diagnosing this issue. I would greatly appreciate any insights or suggestions on where to start digging deeper into this problem.

Thanks in advance for your help!

Update: New Solution Found

For those who have tried the following solutions without success:

  • ALTER SEQUENCE django_migrations_id_seq RESTART WITH {seq_num};
  • SELECT setval('django_migrations_id_seq', (SELECT MAX(id) FROM django_migrations))
  • python manage.py sqlsequencereset MyApp | python manage.py dbshell

I have found another solution on the internet that worked for me:

SELECT
   setval(pg_get_serial_sequence('django_migrations', 'id'), max("id"))
FROM
   "django_migrations";

When I tried select pg_get_serial_sequence('django_migrations','id'), I got public.django_migrations_id_seq1 (Note the extra ‘1’ at the end) This explains the issue I was facing.

It’s wasn’t caused by installing django-simple-history. Instead, it occurred after using navicat to transfer from an old database to a new one, followed by python manage.py migrate.

Thanks to everyone who visits this post, and I hope my findings can help others.

To expand on this slightly, this error will occur at some point in time after you insert rows into the database with specifying the primary key.

1 Like