在 Python ORM Pony中,如果我尝试插入一条记录但它已经存在,我想尝试更新记录。
当记录已经存在时,我收到以下错误:
pony.orm.core.TransactionIntegrityError: Object Record[1234] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: Record.id
编辑:但是,即使我尝试更新记录,似乎也会重新抛出此错误。这是我高度简化的示例代码:
#!/usr/bin/env python
# encoding: utf-8
from pony.orm import *
db = Database()
class Record(db.Entity):
id = PrimaryKey(int)
db.bind("sqlite", "database.sqlite", create_db=True)
db.generate_mapping(create_tables=True)
records = [{"id":1234},{"id":1234}]
@db_session
def saveRecords(records):
for r in records:
try:
Record(**r)
except Exception as e:
print("error caught")
p = Record.get(id=r.get("id"))
p.set(**r)
saveRecords(records)
想法?