Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 886
nacho c Avatar asked Dec 07 '22 19:12

nacho c


1 Answers

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

like image 161
armonge Avatar answered Dec 11 '22 10:12

armonge