Created
April 6, 2021 13:43
-
-
Save MitchellKehn/66742d9de7277b2fc24e346b81f1045a to your computer and use it in GitHub Desktop.
[SQLAlchemy ORM Pretty Repr] #orm #sqlalchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
# monkey-patch a nice __repr__ method onto the Base class. | |
def _niceRepr(self): | |
""" | |
Nicely format class name and column values. | |
Looks up the inheritance hierarchy for inherited columns and displays those too. | |
""" | |
attrs = [] | |
for cls in [self.__class__] + list(self.__class__.__mro__): | |
if not hasattr(cls, "__table__"): break | |
for key in cls.__table__.columns.keys(): | |
if key not in attrs: | |
attrs.append(key) | |
return "<{}: {}>".format( | |
self.__class__.__name__, | |
", ".join(["{}={}".format(attr, repr(getattr(self, attr))) for attr in attrs]) | |
) | |
Base.__repr__ = _niceRepr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment