具有唯一“set”值的SqlAlchemy bulk upsert(Postgres)

2024-03-29 07:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用SqlAlchemy和Postgres执行一个大容量的upsert,其中所有被upsert的行都会收到一组惟一的值,以便在发生冲突时进行更新。在

我更希望在不使用for循环的情况下,这样总体上只执行一个SQL语句。有没有办法做到这一点?在

以下是我目前的情况。当使用.on_update_do_nothing方法时,此方法可以正常工作。我想知道如何正确地传递每一组值,以便在发生冲突时用正确的信息来更新每个记录,而不是泛型值。据我所知,尝试类似问题答案中建议的excluded数据并不能解决这个问题,因为{}需要的是值字典,而不是列表。在

def bulkUpsert(self, items, unique_fields):
  """
  Either inserts items into the table of supplied schema or does nothing.
  Requires items to be mapped prior to being passed to this method.
  """
  try:
    statement = postgresql \
      .insert(self.SCHEMA.__table__) \
      .values(items) \
      .on_conflict_do_update(
        index_elements = unique_fields,
        set_ = What to put here?
      )

    self.SESSION.execute(statement)
    self.SESSION.commit()

  except SQLAlchemyError as err:
    print("Error with bulk insert: %s" % (err))

当前,items参数是一个字典列表,当


Tags: to方法selffields列表字典on情况