I am currently on Building RESTful APIs with Django RESET Framework lesson 15 Saving Objects.
After updating my ProductSerializer fields to:
fields = [‘id’, ‘title’, ‘description’, ‘slug’, ‘inventory’, ‘unit_price’, ‘price_with_tax’, ‘collection’]
And when I go to http://127.0.0.1:8000/store/products/ and input the following object to the POST field:
{
“title”: “test”,
“slug”: “a”,
“inventory”: 1,
“unit_price”: 1,
“collection”: 1
}
It gives me the following error:
duplicate key value violates unique constraint “store_product_pkey”
DETAIL: Key (id)=(11) already exists.
I would not recommend touch database directly at all. Check your views and models and templates. Your error comes because you are trying to add new object with same id which should be unique. I can not give you other suggestion unless I can see a code
Hello sorry for the late reply.
if you’re still having this problem.It’s cause instead of table name you need to write the actual name of your table. In this case store_product.
And for the first argument you pass in ‘store_product_id_seq’.
Thank you! I was having the same issue and your code helped me to solve that problem
I am using PostgreSQL and pgadmin4 and the following query helped to solve the issue
POSTGRESQL15: I ran into the same issue. Due to whatever reason, after the import of the demo data, the internal id_sec counter for the table store_product was at 6, although 1000 records were inserted. As the field is a primary key (pk) field with auto-increment, one would expect, the internal counter id_sec is at 1000. But nope.
So first, we need to check the current value of the id_sec counter: SELECT last_value FROM store_product_id_seq;
=> this gave me a result of 6 (and remember the Django error message: "duplicate key value violates unique constraint “store_product_pkey” DETAIL: Key (id)=(6) already exists.")
Seems we just found the culprit: obviously if the field id is a primary key, no double entries of the same value is allowed. Each record must have its own unique id number. We have 1000 records in the table, means ids from 1 to 1000 are already taken, so, if we insert a new record with the id of 6 it must obviously fail! And that’s the error message.
Next we need to find out where the counter should be by checking the highest value in the field ‘id’: SELECT max(id) FROM store_product;
This returned a value of 1000. Of course, we have 1000 records that were inserted at once by the SQL script from Mosh.
And finally we need set the internal counter ‘id_sec’ to the correct value which is 1000: SELECT setval(‘store_product_id_seq’, 1000, true);
Problem solved. Now try the code again and it will work.
The +1 shouldn’t be needed. The internal id_sec counter should be identical to the highest value of id as otherwise you will leave one out with the next insert operation.