2014-07-25 91 views
0

我有以下的在我的Django模型,我與PostgreSQL的基本處理

class Business(models.Model): 
    location = models.CharField(max_length=200,default="") 
    name = models.CharField(max_length=200,default="",unique=True) 

使用在我看來,我有:

高清saveBusiness(BS):

from ml1.models import Business 

    for b in bs: 
     p =Business(**b) 
     p.save() 

    return 

當應用程序運行和entryis遇到重複列,而不是令人驚訝,我得到

IntegrityError ...duplicate key value violates unique constraint 

我希望ORM根本不插入新記錄並移到下一個記錄上,如果該字段沒有崩潰重複。這在django中最好如何處理?

+0

答案就在這裏http://stackoverflow.com/questions/7143635/django-save-錯誤。謝謝 – user61629

回答

1

最簡單的方法是簡單地趕上並忽略IntegrityError

for b in bs: 
    try: 
     p = Business(**b) 
     p.save() 
    except IntegrityError: 
     pass 

你,如果你正在使用的交易,但要謹慎。看到警告here

發生這樣的錯誤後,事務中斷,Django將在原子塊的末尾執行回滾。如果您嘗試在回滾之前運行數據庫查詢,Django將提出TransactionManagementError

所以,如果你使用的交易你需要用每個迭代在自己atomic()塊:

for b in bs: 
    try: 
     with transaction.atomic(): 
      p = Business(**b) 
      p.save() 
    except IntegrityError: 
     pass 
+0

謝謝凱文 – user61629