Django UUID 字段抛出 IntegrityError
Posted
技术标签:
【中文标题】Django UUID 字段抛出 IntegrityError【英文标题】:Django UUID field throwing IntegrityError 【发布时间】:2015-12-29 02:48:01 【问题描述】:我在现有表中添加了一个UUIDField
,如下所示(由 Postgres 9.4 支持):
class MyTable(TimeStampedModel):
""" """
...
uid = models.UUIDField(default=uuid.uuid4, unique=True,
editable=False,
help_text="Unique identifier")
class Meta:
app_label = "core"
db_table = "my_table"
ordering = ['-created']
当我运行迁移时,我看到了以下我认为不可能的错误:
File "/Users/josephmisiti//projects/xxx/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 398, in add_field
self.execute(sql, params)
File "/Users/josephmisiti/projects/xxx/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute
cursor.execute(sql, params)
File "/Users/josephmisiti/projects/xxx/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/josephmisiti/projects/xxx/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/josephmisiti/projects/xxx/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/josephmisiti/projects/xxx/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: could not create unique index "additional_properties_uid_key"
DETAIL: Key (uid)=(c0ca7e2a-87de-42d2-b188-14821a0e207a) is duplicated.
我的印象是 UUID 是独一无二的,这永远不会发生 - 谁能解释为什么不是这样! (另外,我以前见过这个)
【问题讨论】:
我会假设迁移中的默认值生成一次并应用于所有现有记录(这很可能),或者您遇到了冲突(这不太可能)。 这是可复制的吗?我的意思是如果你再次运行迁移,你会得到同样的错误吗?同一个键? 相同的错误不同的键 我也遇到了同样的问题。数据库中没有存储任何内容仍然会引发此错误 【参考方案1】:我提出的解决方案是覆盖 save
方法:
def save(self, *args, **kwargs):
if not self.uid:
self.uid = uuid.uuid4()
super(Model, self).save(*args, **kwargs)
【讨论】:
以上是关于Django UUID 字段抛出 IntegrityError的主要内容,如果未能解决你的问题,请参考以下文章
ValidationError:在 Django 中不是有效的 UUID