繁体   English   中英

在python中插入或更新peewee记录

[英]Insert or update a peewee record in python

在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)

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

取决于数据库。

对于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())

您还可以使用get_or_create方法: httpget_or_create

暂无
暂无

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

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