Search code examples
pythondjangoheroku

Heroku duplicate key value violates unique constraint (django)


Today I deployed my django app on Heroku for the first time (following this tutorial).

The problem is that when I want to modify or add something to the database, I get an Integrity Error which says:

duplicate key value violates unique constraint "app_professore_pkey"

Where Professore is the name of the Model I tried to modify.

I’ve searched a bit online and I’ve seen that probably is because I developed the app on my PC using SQLite and now, on Heroku, it uses PostgreSQL, and those 2 databases works differently. Actually, I don’t have a lot of experience with databases (almost no experience) so I don’t know how to fix this... Maybe modifying something on the Professore model? Or typing something in the Heroku console?

This is the error screen I get, if you need it to help me :)

Thanks in advance and tell me if I wasn’t clear on something (I’m new to StackOverflow too)


Solution

  • You need to resync your primary key fields in Postgres.

    You can access your DB by this command

    python manage.py dbshell

    Just check table name your_database_name=# \dt

    executing below command

    SELECT setval('table_name_id_seq', (SELECT MAX(id) FROM table_name)+1);