Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using Django, and every once in a while I get this error:

IntegrityError: duplicate key value violates unique constraint "myapp_mymodel_pkey"
DETAIL: Key (id)=(1) already exists.

My Postgres database does in fact have a myapp_mymodel object with the primary key of 1.

Why would Postgres attempt to use that primary key again? Or, is this most likely my application (or Django's ORM) causing this?

This issue occurred 3 more times in a row just now. What I've found is that when it does occur it happens one or more times in a row for a given table, then not again. It seems to happen for every table before it completely stops for days, happening for at least a minute or so per table when it does occur, and only happening intermittently (not all tables right away).

The fact that this error is so intermittent (happened only 3 or so times in 2 weeks - no other load on the DB, just me testing out my application) is what makes me so wary of a low-level problem.

share|improve this question
    
Django specifically states that the primary key is generated by the DBMS unless specified - now, I don't know what @orokusaky was doing in his python code, but I ended up on this page because I'm quite confident that I have no code trying to use a specific primary key and I've never seen a DBMS trying to use a wrong one. – mccc Oct 9 '15 at 8:32
up vote 9 down vote accepted

PostgreSQL will not try to insert duplicate values on its own, it is you (your application, ORM included) who does.

It can be either a sequence feeding the values to the PK set to the wrong position and the table already containing the value equal to its nextval() - or simply that your application does the wrong thing. The first one is easy to fix:

SELECT setval('your_sequence_name', (SELECT max(id) FROM your_table));

The second one means debugging.

Django (or any other popular framework) doesn't reset sequences on its own - otherwise we would have similar questions every other day.

share|improve this answer

I ended up here with very same error, which was occurring rarely, and was hard to track, because I was looking for it not where I should.

Fault was JS repetition which was doing the POST to the server twice! So sometimes it is worth to have a look not only on your django (or any other web framework) views and forms but also what happens on very front side.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.