python - Q : SQLAlchemy 1. 4 (2.0) 从 session.execute(statement).scalars().all() 或 session.execute(statement).all() 转换结果时出现问题

标签 python sqlalchemy

我把这张表定义如下

class Carrier(Base):
    __tablename__ = 'Carrier'
    __table_args__ = {'comment': 'Carrier Code List'}

    Id = Column(Integer, primary_key=True, comment='PK for carrier table')
    Code = Column(String(50), index=True, comment='code to use')
    Description = Column(String(255), comment='description of the code')

要查询我使用以下的表

with Session(self.sqlengine, future=True) as session:
        statement = select(Carrier)
        #result = session.execute(statement).all()
        result = session.execute(statement).scalars().all()

我可以按如下方式循环遍历结果

 for row in result:
    print(row.Id, row.Code)

根据文档,应该返回以下内容

# list of tuples
result = session.execute(statement).all()

# list of first element of each row (i.e. User objects)
result = session.execute(statement).scalars().all()

这就是我感到困惑的地方。我没有得到元组列表或每行的第一个元素。我正在获取该类实例的地址。例如 <0x000001B30ACB1D00 处的载体对象>

如果它实际上返回一个元组或一个具有我在表类中定义的属性的类,那就太好了,但事实并非如此。

我也未能将其转换为有用的类。

如果我应该做一些映射或转换,我不知道如何也找不到示例。我觉得文档也不是很好,至少对于 1.4/2.0

我将不胜感激,我知道我在如何转换方面遗漏了细微差别,但我不知道如何继续。

最佳答案

对于这个设置

with sa.orm.Session(engine, future=True) as session:
    # create test data
    session.add_all([Carrier(Code="Alfa"), Carrier(Code="Bravo")])
    session.commit()
    
    # define our select statement
    statement = sa.select(Carrier)
    
    results = session.execute(statement).all()
    print(results)
    # [(<Carrier(Id=1, Code='Alfa')>,), (<Carrier(Id=2, Code='Bravo')>,)]

版本 1.4 返回 Row 的列表对象。它们类似于元组,并以与元组相同的方式表示,用圆括号包围:(<Carrier(Id=1, Code='Alfa')>,) .

使用 .scalars()

    results = session.scalars(statement).all()
    print(results)
    # [<Carrier(Id=1, Code='Alfa')>, <Carrier(Id=2, Code='Bravo')>]

返回“普通”(“标量”)列表 Carrier对象。请注意,它们未包含在 ( …,) 中。 . .scalars()每个调用“向内看”Row对象并返回它找到的第一个元素(默认为 index=0 )。

使用简单的标量值更容易看出差异:

    statement = sa.select(Carrier.Id)  # just the .Id column
    
    results = session.execute(statement).all()
    print(results)
    # [(1,), (2,)]
    
    results = session.scalars(statement).all()
    print(results)
    # [1, 2]

关于python - Q : SQLAlchemy 1. 4 (2.0) 从 session.execute(statement).scalars().all() 或 session.execute(statement).all() 转换结果时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66974718/

相关文章:

python - Tkinter .after 方法卡住窗口?

python - Numpy einsum 沿轴计算外积

python - 使用 SQL Alchemy 和 pymssql 指定故障转移合作伙伴

python - 使用 SQLAlchemy 列出数据库表

python - 操作错误 : MySQL Connection not available

python - RQ Flask Heroku worker 应用上下文

python - 为什么必须调用 db.session.remove()?

Python:将照片上传到 photobucket

python - 使用整数索引访问 pandas Multiindex Dataframe

python - 属性错误 : module 'tensorflow' has no attribute 'GraphDef'