[Fixed]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey"

29πŸ‘

βœ…

I have tried the above answers, but those did not help me.

Django has built in command to solve this problem.

python manage.py sqlsequencereset auth | python manage.py dbshell

The proper explanation for why this occurs and what the above command does can all be found in this blog post

πŸ‘€jibin mathew

5πŸ‘

I solved this by first running

SELECT last_value FROM auth_permission_id_seq;

to see what the latest sequence number was (for me it was 80), then I set it to a larger value:

ALTER SEQUENCE auth_permission_id_seq RESTART WITH 100;

πŸ‘€elimisteve

4πŸ‘

You have to reset the auth_permission_id_seq as it is most likely lower than the maximum id

SELECT MAX(id)+1 FROM auth_permission
ALTER SEQUENCE auth_permission_id_seq RESTART WITH <result of previous cmd>;

Where 100 is the MAX(id)+1. There is probably a way to do this in one command but my SQL knowledge is limited.

The following will show you the current value of the sequence number and not the one you have to set it to (as it can be way off the MAX(id) in auth_permission)

SELECT last_value FROM auth_permission_id_seq;

I personally had the same issue when I restored the dump (data only) of the production database to the development one.

πŸ‘€nbeuchat

0πŸ‘

Without much other context, it looks like you’ve added a unique constraint to your model, but you have rows in your database that violate this constraint, so the migration fails. So, in your database, you have two rows where auth_permission_pkey == 241.

You need to remove or change this row so it is unique, and re-run your migration.

πŸ‘€rob

Leave a comment