Skip to content

Instantly share code, notes, and snippets.

@mliberty1
Last active July 17, 2018 02:29
Show Gist options
  • Save mliberty1/b48d48fc1b6eb080412129e596ab2193 to your computer and use it in GitHub Desktop.
Save mliberty1/b48d48fc1b6eb080412129e596ab2193 to your computer and use it in GitHub Desktop.
Create automatic, meaningful, ordered repr for Flask-SQLAlchemy models.
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def db_model_repr(self):
"""Create a automatic meaningful repr for db.Model classes
Usage example:
class MyClass(db.Model):
__repr__ = db_model_repr
"""
fields = [str(x).split('.')[-1] for x in self.__table__.c]
values = ["{}={!r}".format(field, getattr(self, field)) for field in fields]
return "{}({})".format(self.__class__.__name__, ', '.join(values))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment