简体   繁体   English

django ORM对唯一列IntegrityError的基本处理

[英]Basic handling of unique column IntegrityError with django ORM

I have the following in my django model, which I am using with PostgresSql 我的Django模型中有以下内容,该模型与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): 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. 如果字段重复而没有崩溃,我想让ORM根本不插入新记录并移至下一条记录。 How is this best handled in django? 如何最好地在Django中处理?

The simplest approach is to simply catch and ignore the IntegrityError : 最简单的方法是简单地捕获并忽略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. 发生此类错误后,交易将中断,并且Django将在原子块的末尾执行回滚。 If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError . 如果尝试在回滚发生之前运行数据库查询,则Django将引发TransactionManagementError

So if you're using transactions you need to wrap each iteration in its own atomic() block: 因此,如果您使用事务,则需要将每个迭代包装在其自己的atomic()块中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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