gpt4 book ai didi

python - 在 python 中插入或更新一条 peewee 记录

转载 作者:太空狗 更新时间:2023-10-29 22:15:31 54 4
gpt4 key购买 nike

有没有一种在 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 和 SQLite 3.24 及更新版本,peewee 3.x 提供对 ON CONFLICT 子句的完整支持。请注意,您可以对 MySQL 使用“on_conflict”API——限制是它不支持“UPDATE”操作。请参阅文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#OnConflict

例子:

# Works with MySQL (which use "REPLACE")
result = (Emp
.insert(first='mickey', last='dog', empno='1337')
.on_conflict('replace')
.execute())

# Works with Postgresql and SQLite (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

关于python - 在 python 中插入或更新一条 peewee 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33485312/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com