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

SQLAlchemy执行.query().all()后返回模型对象而非查询值的原因

问题原因

你当前的输出是SQLAlchemy ORM查询的正常返回结果:调用Session.query(模型类).all()时,默认会将数据库每行数据封装为你定义的StandardRouting类的实例对象,默认的实例字符串表示仅会输出类名和内存地址,不代表没有查询到字段数据。

解决办法
  • 方法1:直接访问实例属性获取字段值
    ORM 映射的字段对应实例的属性,直接用.运算符访问即可:
# 遍历输出所有行的指定字段
for routing_obj in data:
    print(routing_obj.id, routing_obj.platform_name, routing_obj.delivery_type)
  • 方法2:给模型类添加to_dict方法,一键转换为字典
    在StandardRouting类中添加转换方法,后续可以直接导出整行的字典格式数据:
class StandardRouting(Base):
    __tablename__ = 'standard_routing'
    # 原有字段定义保持不变
    __table_args__ = (
        {'schema': 'routing'},
    )

    # 新增转换方法
    def to_dict(self):
        return {column.name: getattr(self, column.name, None) for column in self.__table__.columns}

使用方式:

# 转换为字典列表
data_dict_list = [obj.to_dict() for obj in data]
# 打印即可看到所有字段值
print(data_dict_list)
  • 方法3:查询时直接返回字段值,不获取模型实例
    如果不需要用到ORM的对象操作能力,可以修改查询语句直接返回字段值:
# 返回所有字段组成的元组列表
data = Session.query(*StandardRouting.__table__.columns).all()

# 也可以指定返回的字段
data = Session.query(StandardRouting.id, StandardRouting.platform_name).all()
  • 方法4:重写__repr__方法,让打印实例时直接显示字段值
    在StandardRouting类中添加__repr__方法自定义打印格式:
class StandardRouting(Base):
    # 原有定义保持不变
    def __repr__(self):
        return f"<StandardRouting(id={self.id}, platform={self.platform_name}, delivery_type={self.delivery_type})>"

后续直接打印data就会输出你自定义的字段内容,不会再显示内存地址。

内容的提问来源于stack exchange,提问作者Chau Loi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:15:01