Reputation: 9974
I added a UUIDField
to an existing table as follows (backed by 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']
And when I run a migration, am seeing the following error which I thought was impossible:
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.
I was under the impression that UUIDs were unique and this would never happen - can someone explain why this is not the case! (also, I have seen this before in the past)
Upvotes: 4
Views: 909
Reputation: 9974
The solution I came with was overriding the save
method on models.py
file:
def save(self, *args, **kwargs):
if not self.uuid:
self.uuid = uuid.uuid4()
super(Model, self).save(*args, **kwargs)
Upvotes: 1