You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLAlchemy ORM执行select返回仅显示内存地址的对象问题求助

问题原因

你遇到的现象由两个可独立解决的问题共同导致:

  • 用session.execute()执行ORM实体查询时,返回的迭代器元素是Row容器对象,而非直接的UserMap实例。你执行select(UserMap)时,每个Row对象仅包含1个元素,就是对应的UserMap实例,直接打印Row就会显示为包裹了内存地址的元组形式。
  • 你的UserMap模型没有定义__repr__方法,Python打印自定义类实例时默认只会输出类名和内存地址,部分声明式模型的属性默认不会被objprint直接扫描。
解决方法

1. 正确提取ORM实例

SqlAlchemy 2.x针对整实体查询提供了简化的结果提取方法,不需要手动从Row中取值:

取多个结果

stmt = select(UserMap).where(UserMap.google_auth == '***********************')
with Session(engine) as session:
    # 加.scalars()直接返回UserMap实例迭代器,无需处理Row
    for user in session.execute(stmt).scalars():
        # 直接访问字段即可
        print(user.id, user.google_auth)

取单个结果

with Session(engine) as session:
    # scalar_one_or_none()会直接返回匹配的第一个实例,无结果则返回None
    user = session.execute(stmt).scalar_one_or_none()

如果你不想用scalars方法,也可以手动解包Row:

for (user,) in session.execute(stmt):
    print(user)

2. 自定义模型的__repr__方法

在你的UserMap模型类中添加__repr__方法,即可直接打印实例看到字段内容:

from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    pass

class UserMap(Base):
    __tablename__ = "你的表名"
    # 你的原有字段定义
    id = ...
    google_auth = ...
    create_time = ...

    # 加入repr方法
    def __repr__(self):
        return f"<UserMap(id={self.id!r}, google_auth={self.google_auth!r}, create_time={self.create_time!r})>"
补充说明

你对2.x API的理解基本正确:旧的Query方法没有被完全废弃,但官方优先推荐使用select()+execute()的2.x风格写法,你当前的查询语句写法没有问题,不需要切换为Query方法。

内容的提问来源于stack exchange,提问作者Matthew Forth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:39:00