Django、Postgresql和IntegrityErrors

2024-04-24 00:03:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的背景是mysql,如果我想插入一条记录,我可以使用insert IGNORE命令,这样我就可以插入行,如果有冲突,就忽略它。在

现在,对于我正在处理的Django项目,我使用postgresql,并在一个循环中发出多个保存。但是,我认为如果我得到一个IntegrityError(我忽略了,请参阅下面的代码),那么我将丢失我试图插入的对象的负载。。我该如何修复:

for thing in things:
    try:
        #potentially dangerous save..
        obj = Thing(stuff=10)
        obj.save()
    except IntegrityError:
        pass

如果说,在第五个循环中,发生了一个整数错误,哪些对象将被插入到数据库中?在


Tags: 项目对象django代码命令objpostgresqlsave
2条回答

这将取决于你如何管理你的交易。在

在Postgres上,如果事务中的一个查询失败,则所有后续查询也将失败,错误为“当前事务已中止,查询将被忽略,直到事务块结束”。在

你应该用transaction.savepoint\u回滚在一个except块中。在

请参考Django docHandling exceptions within PostgreSQL transactions

它给出了下一个例子

a.save() # Succeeds, and never undone by savepoint rollback
try:
    sid = transaction.savepoint()
    b.save() # Could throw exception
    transaction.savepoint_commit(sid)
except IntegrityError:
    transaction.savepoint_rollback(sid)
c.save() # Succeeds, and a.save() is never undone

不忽略错误?在

你写的代码是这样工作的。在

You:    Save all the things.
Django: You're about to violate data integrity in your database.
You:    I don't care.
Django: I can't simply corrupt your data. I'll just throw away 
        the things that would corrupt your data.
You:    That's what I wanted.

虽然这可能适用于某些应用程序,但不适合大多数应用程序。在

您只需要决定应该对违反完整性约束的数据执行什么操作,并且需要首先修复允许错误数据到达save()方法的代码。有关Form and Field Validation的文档可能会有所帮助。在

相关问题 更多 >