Boky
Boky

Reputation: 12084

duplicate key value violates unique constraint in django

I have function for creating new user in django as follows:

def initialize(username, password, email, title, firstName, lastName,  telephoneNumber, mobileNumber, smsActive, for_company_id = 1):
    sUsername = username.lower()
    if len(username) > 30:
        sUsername = username[:30].lower()
    user = User.objects.create_user(sUsername, email, password, last_login=datetime.datetime.now())
    user.first_name = firstName
    user.last_name = lastName
    user.save()
    userProfile = UserProfile(user = user, title = title, telephone = telephoneNumber, mobile = mobileNumber, smsActive = smsActive)
    userProfile.code2Factor = pyotp.random_base32()
    userProfile.forCompanyId = for_company_id
    userProfile.main_updated = datetime.datetime.now()
    userProfile.save()
    return userProfile

Then I do it as follows:

user_profile = initialize(input.user.username, password, '', input.title, input.user.first_name, input.user.last_name, input.telephone, input.mobile, sms_active)
user_profile.user.groups.set([Group.objects.get(id=gr.id) for gr in input.groups])
user_profile.cultureMajor = input.cultureMajor
user_profile.offerTax = input.offerTax if 'offerTax' in input else False
user_profile.user.save()

But when I try to create new user I get error as follows:

duplicate key value violates unique constraint "auth_user_pkey" DETAIL: Key (id)=(21811) already exists.

The id 21811 exists in the database but the last one is 25530.

Why django does not use the first next number for ID?

UPDATE

Upvotes: 7

Views: 9875

Answers (3)

Em.C
Em.C

Reputation: 87

For me the issue was to reset the id in the log.

So you run this
SELECT id FROM 'the_table_name' order by id desc limit 1; The number that is returned you increment by 1. Lets say it's 14, then you set it to 15. SELECT setval('public.the_table_name_id_seq', 15);

Upvotes: 1

Lucas Hendren
Lucas Hendren

Reputation: 2826

This is not an issue with Django

duplicate key violates a unique constraint

This message occurs when you create a duplicate key. In your case, this likely means that the primary key sequence in the table you're working with has become out of sync. This could be because of a manual import, that is often the case with for me when I have had this issue. You have to manually reset the primary key index.

I am not sure what your database is, I will share with you the rough Postgres SQL commands I would use to fix it, the first two allow you to see if it is out of sync and the last one will fix it if so. If this isnt enough/its a different db please comment

SELECT MAX('auth_user_pkey') FROM User;   
SELECT nextval('auth_user_key_sequence');

SELECT setval('auth_user_key_sequence', (SELECT MAX(auth_user_pkey) FROM User)+1);

Upvotes: 9

Boky
Boky

Reputation: 12084

I've solved the problem by executing following code:

BEGIN;
SELECT setval(pg_get_serial_sequence('"auth_permission"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_permission";
SELECT setval(pg_get_serial_sequence('"auth_group_permissions"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_group_permissions";
SELECT setval(pg_get_serial_sequence('"auth_group"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_group";
SELECT setval(pg_get_serial_sequence('"auth_user_groups"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user_groups";
SELECT setval(pg_get_serial_sequence('"auth_user_user_permissions"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user_user_permissions";
SELECT setval(pg_get_serial_sequence('"auth_user"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user";
COMMIT;

Upvotes: 8

Related Questions