简体   繁体   English

在save()期间,Peewee检查“唯一约束失败”

[英]Peewee check for 'UNIQUE contraint failed' during save()

To avoid duplicate entries in a database, it is recommended to use the index feature of the database itself and let it handle the problem automatically. 为避免在数据库中重复条目, 建议使用数据库本身的索引功能,并使其自动处理问题。

I've set up the correct indexes with a peewee migration 我通过peewee迁移设置了正确的索引

migrator.add_index('mymodel', ('column1', 'column2', 'column3'), True),

so now if I try to save a mymodel entry with column1 , column2 and column3 values that already exists, I correctly get an exception thrown at me. 因此,现在,如果我尝试使用已存在的column1column2column3值保存mymodel条目,则可以正确地抛出异常。

The exception looks like this: 异常如下所示:

IntegrityError: UNIQUE constraint failed: mymodel.column1, mymodel.column2, mymodel.column3

My question is: is IntegrityError ever thrown for other possible errors too? 我的问题是:是否也会因为其他可能的错误而抛出IntegrityError If yes, how do I differentiate between duplicate insertion and other errors? 如果是,如何区分重复插入和其他错误?

I want to catch and handle duplicate insertion only , not other errors. 我想捕捉和处理重复插入,而不是其他错误。 Is this possible? 这可能吗?

An IntegrityError is raised by the DB to indicate a constraint violation (a violation of the integrity of the db). DB引发IntegrityError来指示违反约束(违反db完整性)。 From the context of the query you're trying to execute you can try to infer what constraint is violated (eg, adding a user whose username already exists, etc). 从您尝试执行的查询的上下文中,您可以尝试推断违反了什么约束(例如,添加用户名已存在的用户,等等)。 But you'll have to dig into the error message itself to differentiate between multiple constraints. 但是,您必须深入研究错误消息本身,以区分多个约束。

If you're doing an UPSERT you can explicitly specify the constraint, but that's kind of a niche usage. 如果您要进行UPSERT,则可以显式指定约束,但这只是一种利基用法。

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

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