1

I'm trying to write a helper function in SqlAlchemy which lets me pass a row from a table and then it will print out the title of each column in that row along with the value stored in each column. The objective is to be able to print off all the attributes of entries without having to call each column individually, and without even needing to know what each column is called.

What I have so far came from this question. It looks like this:

def printModel(model):
      columns = [m.key for m in model.__table__.columns]
      for x in columns:
            print x

someModel = SomeTable.query.get(someID)
printModel(someModel)

All that does so far is print off the names of the columns in that object. Is there a way I can make it print off the name of the columns and the value in each of those columns?

Thanks a lot, Alex

Community
  • 1
  • 1
Alex S
  • 4,726
  • 7
  • 39
  • 67

2 Answers2

1

you can use getattr

def printModel(model):
    columns = [m.key for m in model.__table__.columns]
    for x in columns:
        print x, getattr(model, x)
r-m-n
  • 14,192
  • 4
  • 69
  • 68
1

A neater solution would be to use dict comprehension and the inspect class

from sqlalchemy import inspect
{ c_attr.key:getattr(obj, c_attr.key) for c_attr in inspect(model).mapper.column_attrs }

while leveraging the getattr of course.

Rambatino
  • 4,716
  • 1
  • 33
  • 56