在 python 中插入或更新一条 peewee 记录
Insert or update a peewee record in python
是否有一种使用 peewee
in 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)
我没有看到 "create or update" 命令,但也许我遗漏了什么。
取决于数据库。
对于 Sqlite 和 MySQL,peewee 3.x 支持插入或替换。请参阅文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.replace
对于 Postgresql 和 SQLite 3.24 and newer, peewee 3.x offers complete support of the ON CONFLICT clause. Note that you can use the "on_conflict" APIs with MySQL -- the restriction is that it doesn't support the "UPDATE" action. See docs: 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
是否有一种使用 peewee
in 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)
我没有看到 "create or update" 命令,但也许我遗漏了什么。
取决于数据库。
对于 Sqlite 和 MySQL,peewee 3.x 支持插入或替换。请参阅文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.replace
对于 Postgresql 和 SQLite 3.24 and newer, peewee 3.x offers complete support of the ON CONFLICT clause. Note that you can use the "on_conflict" APIs with MySQL -- the restriction is that it doesn't support the "UPDATE" action. See docs: 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