在Python中使用peewee
是否存在简单的单行方式,如果主键不存在则插入记录,或者如果记录已经存在则更新记录。
目前我正在使用代码:
try:
sql_database.create(record_key = record_key, record_data_2 = record_data_2)
except IntegrityError: ## Occurs if primary_key already exists
sql_database.update(record_key = record_key, record_data_2 = record_data_2)
我看不到“创建或更新”命令,但也许我错过了一些东西。
答案 0 :(得分:10)
取决于数据库。
对于SQLite和MySQL,peewee 3.x支持INSERT OR REPLACE。请参阅文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.replace
对于Postgresql,peewee 3.x完全支持ON CONFLICT子句。请注意,您可以使用" on_conflict"使用SQLite和MySQL的API - 限制是他们不支持" UPDATE"行动。请参阅文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#OnConflict
示例:
# Works with SQLite and MySQL (which use "REPLACE")
result = (Emp
.insert(first='mickey', last='dog', empno='1337')
.on_conflict('replace')
.execute())
# Works with Postgresql (which supports ON CONFLICT ... UPDATE).
result = (Emp
.insert(first='foo', last='bar', empno='125')
.on_conflict(
conflict_target=(Emp.empno,),
preserve=(Emp.first, Emp.last),
update={Emp.empno: '125.1'})
.execute())
您还可以使用get_or_create
方法:http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=get_or_create#Model.get_or_create