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 = model
Solution 1:
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
Post a Comment for "Basic Handling Of Unique Column Integrityerror With Django Orm"