nacho c
nacho c

Reputation: 311

Python/ Django Key already exists. Postgres

I Have a project built in django and it uses a postgres database. This database was populated by CSVs files. So when I want to insert a new object I got the error "duplicated key" because the object with id = 1 already exists.

The code :

user = User(name= "Foo")
user.save()

The table users has the PK on the id.

Indexes:
    "users_pkey" PRIMARY KEY, btree (id)

If I get the table's details in psql I got:

Column| Type    |  Modifiers                          
------+-------- +--------------------------------------
id    | integer | not null default nextval('users_id_seq'::regclass)

Additionally, if I do user.dict after create the variable user and before saving it, I get 'id': None

How can I save the user with an id that is not being used?

Upvotes: 6

Views: 13561

Answers (4)

akarca
akarca

Reputation: 1516

You can fix it by setting users_id_seq manually.

SELECT setval('users_id_seq', (SELECT MAX(id) from "users"));

Upvotes: 8

Ankur Srivastava
Ankur Srivastava

Reputation: 923

In Postgres SQL you can specify id as serial and you can mark it as Primary Key.Then whenever you will insert record , it will be in a sequence. i.e id serial NOT NULL and CONSTRAINT primkey PRIMARY KEY (id).

As you said its a pre populated by CSV , so when you insert it from python code it will automatically go the end of the table and there will be no duplicate values.

Upvotes: 0

armonge
armonge

Reputation: 3138

You most likely inserted your Users from the CSV setting the id value explicitly, when this happens the postgres sequence is not updated and as a result of that when you try to add a new user the sequence generates an already used value

Check this other question for reference postgres autoincrement not updated on explicit id inserts

The solution is what the answer for that question says, update your sequence manually

Upvotes: 11

Raja
Raja

Reputation: 6443

Unless you have name as a primary key for the table the above insert should work. If you have name as primary key remove it and try it.

Upvotes: 0

Related Questions