我想知道如何运行一个查询,仅当一个项不存在时才将其插入到数据库中。我使用json作为实体,所以它们看起来像这样:
class Person(db.Entity):
json = Required(Json)
name = "Alice"
if not Person.exists(lambda person: person['name'] == name):
Person(json={'name': name, """ lots more fields """})但这似乎执行了两个查询,这会减慢操作速度。理想情况下我想要像这样的东西
Person.insert_if_not_exists(json={...})这到底有没有可能?
发布于 2018-08-03 19:43:14
目前小马还不支持get_or_create作为单一命令,我们计划稍后添加它
发布于 2019-08-14 17:46:14
我认为您必须在插入过程中捕获重复异常,如下所述:
try:
with pony.orm.db_session:
table(**row)
except pony.orm.core.TransactionIntegrityError as e:
if 'UNIQUE constraint failed' not in unicode(e):
# Ignore duplicate
else:
raisehttps://stackoverflow.com/questions/49044709
复制相似问题