python - Print an sqlalchemy row -


all i'd print single row of sqlalchemy table row.

say have:

from sqlalchemy import column, integer, string 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 output looks this:

id: 1 name: therowname 

preferable without having hard code in table columns, i.e. more generally.

i've tried:

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

as thought implementing __str__ , __repr__, again lack generality request.

there many questions on covering table row json, that's not want, care more visual output - doesn't need machine readable afterwards.

to clear - want general method print "col: value" without hardcoding column names? not use sqlalchemy much, __str__ method should work:

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

you can put method in mixin class use elsewhere in models.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -