我正在写一个sqlalchemy upsert语句,我想知道是否有办法可以从数据库取回ID?
到目前为止,这是我的代码:
def handle_events(self, events):
agg = []
agg.extend(self._get_dicts(events))
if not agg:
return
with DB.session(writable=True) as session:
response = session.execute(self._generate_upsert_stmnt(agg))
def _generate_upsert_stmnt(self, items):
model_class = models.MyModel
table = model_class.__table__
insert_statement = sa.dialects.postgresql.insert(table, items)
upsert_statement = insert_statement.on_conflict_do_update(
index_elements=[table.c['id']],
set_={c.name: c for c in insert_statement.excluded if c.name != ["id", "my_model", "my_model_id"]}
)
return upsert_statement
此代码段中的会话是来自sqlalchemy的api(包装在上下文管理器中)的sessionmaker调用返回的对象。有没有办法使此upsert语句返回所有id的背面(插入和更新)?如果是这样,该代码将如何显示?
提前致谢。 ps。如果很重要,数据库就是postgres。
最佳答案
最终,我在upsert语句中使用了.returning(<column>)
,如下所示:
def _generate_upsert_stmnt(self, items):
model_class = models.MyModel
table = model_class.__table__
insert_statement = sa.dialects.postgresql.insert(table, items)
upsert_statement = insert_statement.on_conflict_do_update(
index_elements=[table.c['id']],
set_={c.name: c for c in insert_statement.excluded if c.name !=
["id", "my_model", "my_model_id"]}).returning(table.c['id'])
return upsert_statement
并像这样提取数据:
def _extract_ids_from_resultproxy(self, result):
table = models.MyModel.__table__
return [row[table.c.id] for row in result]