Django Saving Objects

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.

Please help… I’m stuck :frowning:

Hi
There is nothing wrong with your django project.
You’re getting this error because of a problem in your mysql database.

You can run this SQL statement in your database to fix this:

ALTER TABLE products AUTO_INCREMENT= the last id number in your products table + 1

I am using PostgreSQL, not mySQL. You think this is the reason why? Thanks!

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

This is the code for PostgreSQL:

SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);

here is the full discussion on StackOverFlow about this issue in Django and PostgreSQL:
https://stackoverflow.com/questions/11089850/integrityerror-duplicate-key-value-violates-unique-constraint-django-postgres

Sorry… One more question. When I tried the method that you suggested, it gives me the ERROR: relation “table name” does not exist

What should be the table name to use?

I’ve dowloaded Mosh’s code and still ran into the same problem… :frowning:

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’.

This is the exact code for PostgreSQL:

select setval(‘store_product_id_seq’, (select max(id) from store_product) + 1);