创建一个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吗
您的代码不会创建唯一的ID,而只是一个随机ID。运行makeUniqueLongId()的频率越高,最终获得重复ID的可能性就越高
Django的unique=True将防止在条目的值已经存在时保存该条目,这正是出现错误的原因(请参阅文档here)。此外,由于您正在设置primary_key=True,因此不需要使用unique,因为该条件将自动设置
尝试向模型中添加自定义save()方法:
相关问题 更多 >
编程相关推荐