Search code examples
pythonsqlalchemy

access fields by column name in SqlAlchemy raw select


games = session.execute(statement=text('select game.id as id, * from game')).all()
for game in games:
  print(game['id'])

I get `tuple indices must be integers or slices, not str'. How can I access the fields by column names and not by index?


Solution

  • You should be able to use dot-notation instead of subscript notation:

    $ 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