Recently I’ve been required to write up some code for manipulating a bunch of sales data and unfortunately that data is massive. We are talking 15+ columns massive.
Now I’m lazy and really like the whole DRY concept since it helps keep me lazy. I chose to use SQLAlchemy for managing my data within the database and as such have objects that I can access in ways such as:
object.foo
This is alright, but remember I have 15+ columns to deal with here. I really don’t want to be writing out each line in my templates or whatever I have for when I displaying the data. Also, if this object changes for whatever reason, I would need to go in and change the view code as well.
Ugh… Makes me work more.
DO NOT WANT.
After a bit of searching on the Internet I’ve come across a few things that can be useful for us. We can firstly get all columns that exist for a model. By performing Object.__table__.columns we are able to get a list that contains all the columns for our object. Now, for each column we can ask for its name. Excellent!
If only we had a dictionary we would be set. This is possible by asking for the __dict__ of each object in our dataset.
Example:
object = Object.query.all()[0]
columns = Object.__table__.columns
for column in columns:
print "%s is %s" % (column.name, object.__dict__[column.name])
There are probably better ways of doing this, such as simply iterating over the dictionary but since I was stuffing this data into a table I was going to need the columns anyway.
References: