在python中插入或更新peewee记录

kyr*_*nia 7 python peewee

是否有一种简单的单行方式peewee在Python中使用,如果主键不存在则插入记录,或者如果记录已经存在则更新记录.

目前我正在使用代码:

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)
Run Code Online (Sandbox Code Playgroud)

我看不到"创建或更新"命令,但也许我错过了一些东西.

col*_*fer 11

取决于数据库.

对于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"API与SQLite和MySQL一起使用 - 限制是它们不支持"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())
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下get_or_create方法:http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight = get_or_create#Model.get_or_create

  • upsert的问题是,如果在记录上有insert_date,update_date等字段,则不能使用REPLACE.您不知道原始的insert_date是否成功. (2认同)
  • 请注意,“冲突替换”将删除旧行并插入新行,这意味着该记录的 id 将更改。 (2认同)