Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey"

Ran into a bit of a problem, i'm getting the above error message when i run 'python manage.py syncdb' I'm working on a fairly old site. It' running django 1.2.6 with a postgres DB.

The run didn't have south installed and i managed to get that working. Ran python manage.py schemamigration --initial contact_enquiries which ran fine and asked me to migrate. I then ran python manage.py migrate contact_enquiries I then got the same error as above.

It doesn't complaing about any of the syntax in my models which is why i'm confused. Here are my models and hopefully that will shed some light.

from django.db import models

class DocumentUpload(models.Model):
    name = models.CharField(max_length="200")

    document_upload = models.FileField(upload_to="uploads/documents")


    def __unicode__(self):
        return "%s" % self.name

class DocumentRequest(models.Model):
    name = models.CharField(max_length="200")

    company = models.CharField(max_length="200")

    job_title = models.CharField(max_length="200")

    email = models.EmailField(max_length="200")

    report = models.ManyToManyField(DocumentUpload)

    def __unicode__(self):
        return "%s" % self.name

If you need anymore information, please let me know.

Thanks!

like image 674
JDavies Avatar asked Oct 02 '13 10:10

JDavies


2 Answers

Although I am not 100% certain this is the problem, there is a good chance your sequence is out of date.

Does executing this within Postgres solve the issue?

SELECT setval('django_content_type_id_seq', (SELECT MAX(id) FROM django_content_type)); 
like image 101
Wolph Avatar answered Sep 23 '22 10:09

Wolph


This usually means that your primary key sequence has gone out of sync. This may have been caused by a bad migration etc..
To fix this;
1. Start the dbshell
python manage.py dbshell
2. Find the current highest value of the primary key
select max(id) from django_content_type;
3. Change the primary key sequence to now start at a value higher than the value found in step 2.
So assuming the value returned in step 2 was 290780 then alter sequence to start at a number greater than 290780
alter sequence django_content_type_id_seq restart with 295000;

like image 29
Komu Avatar answered Sep 21 '22 10:09

Komu