简体   繁体   中英

Basic handling of unique column IntegrityError with django ORM

I have the following in my django model, which I am using with PostgresSql

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

In my view I have:

def saveBusiness(bs):

    from ml1.models import Business

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

    return

When the app is run and a duplicate column entryis encountered, not suprisingly I get

IntegrityError ...duplicate key value violates unique constraint

I would like to have the ORM simply not insert the new record and move onto the next record, if the the field is duplicated without crashing. How is this best handled in django?

The simplest approach is to simply catch and ignore the IntegrityError :

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

You have to be cautious if you're using transactions, though. See the warning here :

After such an error, the transaction is broken and Django will perform a rollback at the end of the atomic block. If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError .

So if you're using transactions you need to wrap each iteration in its own atomic() block:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM