[Fixed]-Django db migration failed with postgres


I overlooked the name of the ‘django_migrations_pkey’ column and I didn’t realize that was in the database. Somehow django was one step behind the actual database and trying to use the primary key (pk=27) instead of the number it was actually on (which should have been 28)

I was unsure about how to change this from within django so instead I just deleted the last column from the database so it was one primary key shorter and on track with django and it started working just fine.



There is another way. Since you know the last id value in django_migrations table, say it is 100. Then, you need to do this:

ALTER SEQUENCE django_migrations_id_seq RESTART WITH 101;


I got this error after I had previously manually tinkered with the django migrations tables entries (after some previously dodgy migrations were added then removed).

This left the django_migrations IDs out of order (so to speak) with the default position of the entry in the django_migrations table.

The issue is that django takes the ID of the last entry and +1 to create a new entry (in table below: 197 + 1 = 198), however as you can see Key (id)=(198) already exists in the table.

187 | foo_app             | 0016_auto_20161220_2332                     | 2017-01-06 05:22:07.666172+00
198 | bar_app             | 0004_auto_20160423_2122                     | 2017-01-13 05:38:31.922738+00
197 | baz_app             | 0013_auto_20170203_2311                     | 2017-02-08 18:50:22.70143+00

As you can see the numbers for the primary key on the left are out of order.
What I did was manually delete the out of order entries in the django_migration then re-add them.

DELETE from django_migrations where name = '0004_auto_20160423_2122';
DELETE from django_migrations where name = '0013_auto_20170203_2311';

INSERT INTO django_migrations VALUES (188, 'baz_app', '0013_auto_20170203_2311', date());
INSERT INTO django_migrations VALUES (189, 'bar_app', '0004_auto_20160423_2122', date());

Also of note is that the migration that I was initially trying to add ‘new_app, ‘0002_auto_00000000_1111’ actually modified the new_app table in postgres, however the django_migrations table didn’t get updated.

So the second time I tried to re-run the migration 0002_auto_00000000_1111 I got the error:

django.db.utils.ProgrammingError: column "new_app_field" of relation "new_app_new" already exists

My solution above fixed the problem for me.


Simply reindexing the django_migrations table worked for me.

Follow these steps in your terminal

Change user to root

$ sudo su

So that you can then then change user to postgres

$ su postgres

Open postgres terminal client with your db selected

$ psql name_of_your_db

In the postgres client issue the following command

REINDEX TABLE django_migrations;

And then quit the postgres client


Leave a comment