2015-12-29 64 views
3

我添加了一個UUIDField現有表如下(由Postgres的9.4的支持):Django的UUID場擲IntegrityError

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

我假設在遷移任一默認值生成一次並施加到所有現有的記錄(很有可能)或者你碰到了(這是不太可能的)。 –

+0

這是可重複的嗎?我的意思是如果你再次運行遷移,你會得到同樣的錯誤嗎?同樣的鑰匙? –

+0

同樣的錯誤不同的密鑰 – josephmisiti

回答

0

我來了與被重寫save方法解決辦法:

def save(self, *args, **kwargs): if not self.uid: self.uid = uuid.uuid4() super(Model, self).save(*args, **kwargs)