【问题标题】:sqlalchemy table.update.returning only returns one value instead of multiple on postgresqlsqlalchemy table.update.returning 在 postgresql 上只返回一个值而不是多个
【发布时间】:2020-08-04 16:40:42
【问题描述】:

我使用postgresqlsqlalchemy,这里是更新一个表,然后使用returning返回多个值:

async def update_monitor(id: int, payload: MonitorIn) -> Dict[str, Any]:
    
    utc_now = to_utc(datetime.now())
    query = (
        MONITOR
            .update()
            .where(id == MONITOR.c.id)
            .values(**payload.dict(), updated=utc_now)
            .returning(MONITOR.c.id,
                       MONITOR.c.watchlist_id,
                       MONITOR.c.term,
                       MONITOR.c.match_substring_variations,
                       MONITOR.c.nameserver_exclusions,
                       MONITOR.c.text_exclusions,
                       MONITOR.c.created,
                       MONITOR.c.updated)
    )
    result = await PRIMARY.execute(query=query)
    return {'id': result[0],
            'watchlist_id': result[1],
            'term': result[2],
            'match_substring_variations': result[3],
            'nameserver_exclusions': result[4],
            'text_exclusions': result[5],
            'created': result[6],
            'updated': result[7]}

PRIMARY 是一个 postgresql 数据库。

import databases
PRIMARY = databases.Database(config.DB_URL)

但是,结果是一个int,它对应于MONITOR.c.id,这是第一个返回值,因此returning 方法似乎只返回一个(第一个)值而不是多个值。我实际上希望返回多个值。并且根据this 它应该支持返回多个值。这里有什么问题?

【问题讨论】:

  • 请定义什么是PRIMARY。您使用什么库来包装 SQLAlchemy 以进行异步/等待?如果您遇到错误,请发布完整的回溯

标签: python postgresql sqlalchemy


【解决方案1】:

它看起来像 databases 库的 execute() returns Cursor.lastrowid,如果你想要结果行 use fetch_one() / fetch_all() / iterate() 代替。

请注意,这不是 SQLAlchemy 和returning() 的行为,正如本问题的标题所暗示的,而是databases 的行为,它只是使用 SQLAlchemy Core DSL 作为一种方式定义查询。然后在后台将它们编译为文本,并使用自己的连接池和正在使用的异步驱动程序将语句发送到数据库。

【讨论】:

  • 你的意思是 result = await PRIMARY.fetch_one(query=query)?我看到结果是 ,如何从中获取行记录?
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 2018-12-05
  • 2017-08-11
  • 1970-01-01
  • 2013-07-07
  • 2020-06-12
  • 2020-02-23
  • 1970-01-01
相关资源
最近更新 更多