Pedro Feijão
Pedro Feijão

Reputation: 121

Django 1.4 primary key conflict after a bulk_create

I am using Django 1.4, with postgresql as the database, and I have the following model:

class Keyword(models.Model):
    name = models.CharField(max_length=100)

I am populating the django database with data from another database, using bulk_create, with some code similar to:

Keyword.objects.bulk_create([Keyword(id=id, name=name) for id,name in [(1,"k1"),(2,"k2"),(3,"k3")] ])

The legacy data has the primary key already, and it is important to keep it this way.

The problem is that when I try to create new objects, Django will use primary keys starting from 1, and a conflict exception is thrown:

k = Keyword(name="k4")
k.save()

gives me the error

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

Is there a way to force Django to start the primary key increment at another value, or any way to solve this conflict?

Upvotes: 5

Views: 2796

Answers (2)

Pedro Feijão
Pedro Feijão

Reputation: 121

I solved this problem by setting the next id in the auto increment logic of postgresql, outside of Django, using the setval command, similar to questions Postgresql setting next id to write to and How to reset postgres' primary key sequence when it falls out of sync?.

In my example, i would have to execute in psql the command

select setval('keyword_id_seq', 3); 

where keyword_id_seq is the name of the auto-increment sequence (by default, <table_name>_<column_name>_seq' ), and 6965 is the maximum id present in the table. That way, the auto-increment starts from the next id (4 in this case) and no conflict happens.

Upvotes: 7

Chamila Chulatunga
Chamila Chulatunga

Reputation: 4914

You can override the default model behaviour of including an auto-incrementing primary key by adding your own id field and marking it as the primary key. E.g:

 class Keyword(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100) 

Docs: Automatic Primary Keys

Upvotes: 2

Related Questions