我在现有表中添加了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是独一无二的,这种情况永远不会发生 - 有人可以解释为什么不是这种情况! (另外,我以前见过这个)
答案 0 :(得分:0)
我带来的解决方案是覆盖save
方法:
def save(self, *args, **kwargs):
if not self.uid:
self.uid = uuid.uuid4()
super(Model, self).save(*args, **kwargs)