I would like to display / print my sqlalchemy classes nice and clean.
In Is there a way to auto generate a __str__() implementation in python? the answer You can it
I define this __repr__
method on my base model:
def __repr__(self):
fmt = '{}.{}({})'
package = self.__class__.__module__
class_ = self.__class__.__name__
attrs = sorted((col.name, getattr(self, col.name)) for col in self.__table__.columns)
sattrs = ', '.join('{}={!r}'.format(*x) for x in attrs)
return fmt.format(package, class_, sattrs)
The method displays the names of all of a table's columns (but not relationships), and the repr
of their values, in alphabetical order. I don't usually define a __str__
unless I need a particular form - perhaps str(User(name='Alice'))
would just be Alice
- so str(model_instance)
will call the __repr__
method.
import datetime
import sqlalchemy as sa
from sqlalchemy.ext import declarative
class BaseModel(object):
__abstract__ = True
def __repr__(self):
fmt = u'{}.{}({})'
package = self.__class__.__module__
class_ = self.__class__.__name__
attrs = sorted((c.name, getattr(self, c.name)) for c in self.__table__.columns)
sattrs = u', '.join('{}={!r}'.format(*x) for x in attrs)
return fmt.format(package, class_, sattrs)
Base = declarative.declarative_base(cls=BaseModel)
class MyModel(Base):
__tablename__ = 'mytable'
foo = sa.Column(sa.Unicode(32))
bar = sa.Column(sa.Integer, primary_key=True)
baz = sa.Column(sa.DateTime)
>>> mm = models.MyModel(foo='Foo', bar=42, baz=datetime.datetime.now())
>>> mm
models.MyModel(bar=42, baz=datetime.datetime(2019, 1, 4, 7, 37, 59, 350432), foo='Foo')