Django and Postgres Duplicate Key

Django Duplicate Key Error Postgres

If you get an error trying to create a django object - in this case app.model.

django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_model_pkey"
DETAIL:  Key (id)=(156) already exists. 

You will need to alter the sequence for this database table. Somehow things got thrown out of order, and django is trying to create a new entry in the database where another entry with that primary key already exists.

Open up a postgres prompt, and then we'll find the current max (id) value, and set the sequence to start from there instead of in this case 156 which causes the conflicting keys.

my_django_db=# select max(id) from app_model;
max
-------
16744
(1 row)

So we see that the current maximum ID in this database is 16744, and we're trying to create the new model with a primary key of 156 which is much lower. We want to set that to 16745, the next number in the sequence.

We can first confirm that the sequence is currently 156, which is wrong, and then we'll alter it.

my_django_db=# select start_value, last_value, max_value from app_model_id_seq;
start_value | last_value | max_value
-------------+------------+---------------------
1 | 156 | 9223372036854775807
(1 row)

We see the last_value is 156 the key that the django error was complaining about. Set it to 16745 and confirm.

my_django_db=# alter sequence app_model_id_seq restart with 16745;

You'll see the postgres console respond with:

ALTER SEQUENCE

Now confirm last_value is 16745.

my_django_db=# select start_value, last_value, max_value from app_model_id_seq;
start_value | last_value | max_value
-------------+------------+---------------------
1 | 16745 | 9223372036854775807
(1 row)
(Comments)

Comments