[Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"

1👍

After restarting the index, I indeed simply deleted/dropped the constraints and indices that were giving “already exists” errors and managed to migrate:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, defender, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  Applying lucy_web.0163_auto_20180627_1309... OK

73👍

This fix is working for my postgreSQL db

Open django shell

python manage.py shell

Run the following Python code to reset id

from django.db import connections

query = "SELECT setval('django_migrations_id_seq', (SELECT MAX(id) FROM django_migrations))"
cursor = connections['default'].cursor()
cursor.execute(query) 
row = cursor.fetchone()

6👍

Run the migrate command repeatedly until the error goes.
On each try it tries to increment the id(pk) value.
Once the increment reaches out the max of existing id, the command runs successfully.

👤LNBabu

0👍

I fixed my Postgres DB with the following queries:

  1. Enter your DB shell with ./manage.py dbshell
  2. Run SELECT id FROM "django_admin_log" ORDER BY id DESC LIMIT 1; and take note of the output (should be an integer like 326)
  3. Run SELECT setval('django_admin_log_id_seq', LASTID + 1); and replace LASTID with the integer you got from the previous command

Leave a comment