python 在SqlAlchemy原始选择中按列名访问字段

5sxhfpxr  于 2023-10-14  发布在  Python
关注(0)|答案(2)|浏览(112)
games = session.execute(statement=text('select game.id as id, * from game')).all()
for game in games:
  print(game['id'])

我得到`元组索引必须是整数或切片,而不是str '。如何通过列名而不是索引访问字段?

zpjtge22

zpjtge221#

您应该能够使用点表示法而不是下标表示法:

$ cat foo.py 
import sqlalchemy as db
from sqlalchemy.sql import text

engine = db.create_engine(<redacted>)
with engine.connect() as session:
  games = session.execute(statement=text('select * from game')).all()
  for g in games:
    print(g.id)

$ python3.11 foo.py 
1
fykwrbwg

fykwrbwg2#

如果出于某种原因,你想要字典式的访问,你可以使用Row的_mapping属性:

with engine.connect() as conn:
    res = conn.execute(text("""SELECT * FROM tbl"""))
    for row in res:
        print(row._mapping['id'])

如果你想让这一行作为一个真正的字典(._mapping的返回值不是真正的dict),那么使用_asdict()方法:

with engine.connect() as conn:
    res = conn.execute(text("""SELECT * FROM tbl"""))
    for row in res:
        row_as_dict = row._asdict()
        # Do something with the dict

一般来说,我们不应该在Python中使用下划线前缀的对象属性,因为下划线表示属性是私有的,但是对于行属性,它们是前缀的,以防止与数据库中的列发生名称冲突。

相关问题