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

使用Sqlalchemy查询返回类对象而非具体值的原因及解决方法

问题原因
  • 使用SQLAlchemy ORM查询时,session.query(模型类)返回的是模型类的实例对象,Python默认打印类实例只会输出类名和内存地址,不会主动展示所有字段的存储值。
  • 你的User模型中Id字段定义为String(20)字符串类型,但过滤条件写的是User.Id == 5传递整数,存在类型不匹配导致查询结果不符合预期的隐患。
解决方法

以下是几种常用的实现方案:

1. 手动读取实例字段

查询得到实例列表后,直接通过属性名访问字段值即可:

def test():
    db_session = sessionmaker(bind=engine)
    session = db_session()
    users = session.query(User).filter(User.Id == '5').all()
    for user in users:
        # 按需读取需要的字段
        print(user.Id, user.ProductName, user.ProductDesc, user.CreationTime, user.ProductCategory)

2. 给模型类添加__repr__方法

在User类中定义__repr__魔术方法,自定义实例的打印格式,后续直接打印实例就会输出指定字段值:

class User(Base):
    __tablename__ = 'Products'
    Id = Column(String(20), primary_key=True)
    ProductName = Column(String(20))
    ProductDesc = Column(String(50))
    CreationTime = Column(String(20))
    ProductCategory = Column(String(50))

    # 新增__repr__方法
    def __repr__(self):
        return f"User(Id={self.Id}, ProductName={self.ProductName}, ProductDesc={self.ProductDesc}, CreationTime={self.CreationTime}, ProductCategory={self.ProductCategory})"

定义完成后直接执行print(user)就可以输出你需要的字段内容。

3. 查询时直接返回字段值

如果不需要模型实例,只想直接拿到字段值,可以在query方法中指定要查询的字段,返回结果为存储具体值的元组列表:

def test():
    db_session = sessionmaker(bind=engine)
    session = db_session()
    # 直接指定要查询的字段
    res = session.query(User.Id, User.ProductName, User.ProductDesc, User.CreationTime, User.ProductCategory).filter(User.Id == '5').all()
    print(res)

4. 实例转字典

如果需要把所有字段转为字典格式,可以通过实例的__dict__属性提取,过滤掉SQLAlchemy自带的内部属性即可:

def test():
    db_session = sessionmaker(bind=engine)
    session = db_session()
    users = session.query(User).filter(User.Id == '5').all()
    for user in users:
        user_dict = {k: v for k, v in user.__dict__.items() if not k.startswith('_')}
        print(user_dict)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:04