0

All I'd like to do is print a single row of an sqlalchemy table row.

Say I have:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class ATable(Base):
     __tablename__ = 'atable'  
     id = Column(Integer, primary_key=True) 
     name = Column(String(255), nullable=False)

Then I'd like to output anything that looks like this:

id: 1
name: theRowName

Preferable without having to hard code in the table columns, i.e. more generally.

I've tried:

 atable = Atable()
 ... #add some values etc.
 print atable
 print str(atable)
 print repr(atable)
 print atable.__table__.c

As well as thought about implementing __str__ and __repr__, but they again lack the generality request.

There are many questions on covering a table row into JSON, but that's not really what I want, I care more about the visual output - it doesn't need to be machine readable afterwards.

2
  • Add __str__ and __repr__ methods respectively to your model, if you wish to alter the representations. Commented Jun 28, 2016 at 9:42
  • Updated with regards to __str__ and __repr__ Commented Jun 28, 2016 at 10:16

1 Answer 1

2

To be clear - you want a general method to print "col: value" without hardcoding the column names? I do not use SQLAlchemy much, but a __str__ method like this should work:

def __str__(self):
    output = ''
    for c in self.__table__.columns:
        output += '{}: {}\n'.format(c.name, getattr(self, c.name))
    return output

You can then put that method in a mixin class to use elsewhere in your models.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, thanks! I ended up making a custom 'printer' which does something similar, though not as elegantly as yours so I will be using your code in my 'printer'. I think I should have been clearer that I had already had a lot of different and changing models and really only one very specific place I wanted to print the rows. So it was less effort having it specific on the outside of the class than change all my models' classes. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.