重复键值违反了Django中唯一的约束

时间:2019-05-24 05:43:22

标签: python django

我具有在Django中创建新用户的功能,如下所示:

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

然后我按如下操作:

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()

但是当我尝试创建新用户时,出现如下错误:

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

ID 21811存在于数据库中,但最后一个是25530

为什么django不使用ID的第一个下一个号码?

更新

  • 用户模型是django的标准模型。
  • UserProfile如下:

    class UserProfile(models.Model):
        forCompanyId = 1
        user = models.OneToOneField(to=User, on_delete=models.DO_NOTHING)
        title = models.CharField(max_length=10, null=True, blank=True)
        telephone = models.CharField(max_length=50, null=True, blank=True)
        mobile = models.CharField(max_length=50, null=True, blank=True)
        smsActive = models.BooleanField(default=False)
        car_by_car_notification = models.BooleanField(default=True)
        car_by_car_mail = models.BooleanField(default=True)
        daily_digest = models.BooleanField(default=True)
        offer_tax = models.BooleanField(default=False)
        cultureMajor = models.CharField(max_length=3, blank=False, default='en')
        cultureMinor = models.CharField(max_length=3, blank=True)
        modulesBlocked = models.ManyToManyField(to=Module, through='UserModuleBlocked')
        otherEmails = models.CharField(max_length=512, null=True, blank=True)
        otherContact = models.CharField(max_length=256, null=True, blank=True)
        browser = models.CharField(max_length=256, null=True, blank=True)
        picture = models.ImageField(upload_to=settings.MEDIA_ROOT, blank=True, null=True)
        code2Factor = models.CharField(max_length=256, null=True, blank=True)
        mobile2Factor = models.BooleanField(default=False)
        authenticator2Factor = models.BooleanField(default=False)
        main_user_id = models.IntegerField(null=True)
        main_updated = models.DateTimeField(_('date updated on main'), default=timezone.now)
    

2 个答案:

答案 0 :(得分:0)

这不是Django的问题

duplicate key violates a unique constraint

创建重复密钥时,会出现此消息。在您的情况下,这可能意味着您正在使用的表中的主键序列已不同步。这可能是由于手动导入,对于我来说,遇到此问题时通常就是这种情况。您必须手动重置主键索引。

我不确定您的数据库是什么,我将与您共享用于修复该数据库的粗糙的Postgres SQL命令,前两个允许您查看它是否不同步,而后一个则可以修复它,如果所以。如果这还不够/它的数据库不同,请发表评论

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);

答案 1 :(得分:0)

我通过执行以下代码解决了这个问题:

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;