8

When I am using SQLALchemy how would one iterate through column names?

Eg.

Column Name 1, Column Name 2, Column Name 3, etc...

The second question is I have the following query:

root = dbsession.query(MyTable).filter(MyTable.name==u'john').all()

However, when I do:

for row in root:
    print row

I don't get any results. Instead I have to do:

print row.name, row.age, etc...

Can't I just do print row to return data from all the columns?

James B. Nall
  • 1,398
  • 3
  • 16
  • 27
sidewinder
  • 3,013
  • 6
  • 24
  • 33

4 Answers4

11

dbsession.query(MyTable).filter(MyTable.name==u'john') will go through ORM and return you objects. If you just want to return all columns, you can bypass ORM with this:

query = dbsession.query(MyTable).filter(MyTable.name==u'john')
rows = query.statement.execute().fetchall()
for row in rows:
    print row
sayap
  • 6,169
  • 2
  • 36
  • 40
3

There is an easier way to iterate through column names without using 'query', and details for accessing tables and columns can be found in the docs here.

Essentially it will look something like this:

metadata = MetaData()
metadata.reflect(engine)
tbl = Table('mytable', metadata)
for column in tbl.c:
    print column.name

I recognize this post is out of date, but this info might still be helpful for someone looking.

ariana
  • 31
  • 1
2

You can do something like this.

rows = MyTable.query.all()
# Get all the column names of the table in order to iterate through
column_keys = MyTable.__table__.columns.keys()
# Temporary dictionary to keep the return value from table
rows_dic_temp = {}
rows_dic = []
# Iterate through the returned output data set
for row in rows:
    for col in column_keys:
        rows_dic_temp[col] = getattr(row, col)
    rows_dic.append(rows_dic_temp)
    rows_dic_temp= {}
return jsonify(rows_dic)
navodissa
  • 55
  • 1
  • 7
  • This is arguably a better answer for the "how do I iterate through columns" part of the question. But who decided that you'd get to a list of column names by calling columns.keys()? Given that we're talking about databases, and most of them are relational, and the term "key" is already defined, critical, and something completely different from a column name? – user3224303 May 09 '23 at 14:18
0

If MyTable is an ORM mapped class, you can define __str__ or __repr__ methods and then it will print the way you want it to. Otherwise you just want to do for row in session.execute(): instead.

underrun
  • 6,713
  • 2
  • 41
  • 53