Skip to content

Add default __repr__ for Model class #530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from Sep 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion flask_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.session import Session as SessionBase

from ._compat import itervalues, string_types, xrange
from ._compat import itervalues, string_types, xrange, to_str

__version__ = '2.2.1'

Expand Down Expand Up @@ -662,6 +662,10 @@ class Model(object):
#: Equivalent to ``db.session.query(Model)`` unless :attr:`query_class` has been changed.
query = None

def __repr__(self):
pk = ', '.join(to_str(value) for value in inspect(self).identity)
return '<{0} {1}>'.format(type(self).__name__, pk)


class SQLAlchemy(object):
"""This class is used to control the SQLAlchemy integration to one
Expand Down
21 changes: 19 additions & 2 deletions flask_sqlalchemy/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"""
import sys


PY2 = sys.version_info[0] == 2


Expand All @@ -25,6 +24,15 @@ def itervalues(d):

string_types = (unicode, bytes)

def to_str(x, charset='utf8', errors='strict'):
if x is None or isinstance(x, str):
return x

if isinstance(x, unicode):
return x.encode(charset, errors)

return str(x)

else:
def iteritems(d):
return iter(d.items())
Expand All @@ -34,4 +42,13 @@ def itervalues(d):

xrange = range

string_types = (str, )
string_types = (str,)

def to_str(x, charset='utf8', errors='strict'):
if x is None or isinstance(x, str):
return x

if isinstance(x, bytes):
return x.decode(charset, errors)

return str(x)
31 changes: 31 additions & 0 deletions tests/test_model_class.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# coding=utf8
import flask_sqlalchemy as fsa
from flask_sqlalchemy._compat import to_str


def test_custom_query_class(app):
Expand All @@ -11,3 +13,32 @@ class SomeModel(db.Model):
id = db.Column(db.Integer, primary_key=True)

assert isinstance(SomeModel(), CustomModelClass)


def test_repr(db):
class User(db.Model):
name = db.Column(db.String, primary_key=True)

class Report(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
user_name = db.Column(db.ForeignKey(User.name), primary_key=True)

db.create_all()

u = User(name='test')
db.session.add(u)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think create_all, add and flush aren't needed here since you don't need a database roundtrip to access the attributes you just set

Copy link
Member

@davidism davidism Sep 26, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, identity_key isn't populated until the object is persisted.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, good point

db.session.flush()
assert repr(u) == '<User test>'
assert repr(u) == str(u)

u2 = User(name=u'🐍')
db.session.add(u2)
db.session.flush()
assert repr(u2) == to_str(u'<User 🐍>')
assert repr(u2) == str(u2)

r = Report(id=2, user_name=u.name)
db.session.add(r)
db.session.flush()
assert repr(r) == '<Report 2, test>'
assert repr(u) == str(u)