正在为新记录创建自定义唯一Id,但存在重复错误

2024-10-03 06:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

创建一个id并尝试插入一条记录,但出现重复错误

django.db.utils.IntegrityError: (1062, "1062 (23000): Duplicate entry '715683160' for key 'projects_project.PRIMARY'", '23000')

import random


def makeUniqueLongId():
  return random.randint(100000000, 999999999)


class Project(models.Model):
  id = models.BigIntegerField(unique=True, primary_key=True, default=makeUniqueLongId(), editable=False)
  ...

如何防止id重复?unique=True不足以返回带有makeUniqueLongId()的新id吗


Tags: djangokeyidtruedbmodels错误记录
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:06

您的代码不会创建唯一的ID,而只是一个随机ID。运行makeUniqueLongId()的频率越高,最终获得重复ID的可能性就越高

Django的unique=True将防止在条目的值已经存在时保存该条目,这正是出现错误的原因(请参阅文档here)。此外,由于您正在设置primary_key=True,因此不需要使用unique,因为该条件将自动设置

尝试向模型中添加自定义save()方法:

def makeUniqueLongId():
  return random.randint(100000000, 999999999)

class Project(models.Model):
  id = models.BigIntegerField(primary_key=True, editable=False)
  ...

# while id is not yet set, create new random id. If random id not already exists, save as new id.

    def save(self, *args, **kwargs):
        while not self.id:
            new_id = makeUniqueLongId()
        if not type(self).objects.filter(id=new_id).exists():
            self.id = new_id
        super().save(*args, **kwargs)

相关问题 更多 >