【问题标题】:Pony Orm - 'Insert if not exists' statementPony Orm - '如果不存在则插入' 语句
【发布时间】:2018-03-01 07:32:52
【问题描述】:

我想知道如何运行一个查询,仅当项目不存在时才将其插入数据库。我使用 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={...})

这可能吗?

【问题讨论】:

标签: python ponyorm


【解决方案1】:

目前 Pony 不支持 get_or_create 作为单个命令,我们计划稍后添加它

【讨论】:

    【解决方案2】:

    我认为您必须在插入过程中捕获重复的异常,如下所述:

        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:
                raise
    

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 2017-06-10
      • 2018-09-17
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多