diff --git a/sqlalchemy_utils/functions/__init__.py b/sqlalchemy_utils/functions/__init__.py index d536df4..01208b6 100644 --- a/sqlalchemy_utils/functions/__init__.py +++ b/sqlalchemy_utils/functions/__init__.py @@ -90,14 +90,22 @@ def primary_keys(class_): yield column -def table_name(class_): +def table_name(obj): """ - Return table name of given declarative class. + Return table name of given target, declarative class or the + table name where the declarative attribute is bound to. """ + class_ = getattr(obj, 'class_', obj) + try: return class_.__tablename__ except AttributeError: + pass + + try: return class_.__table__.name + except AttributeError: + pass def non_indexed_foreign_keys(metadata, engine=None): diff --git a/tests/test_table_name.py b/tests/test_table_name.py index 2cfc19e..234d22f 100644 --- a/tests/test_table_name.py +++ b/tests/test_table_name.py @@ -12,7 +12,14 @@ class TestTableName(TestCase): self.Building = Building - def test_table_name(self): + def test_class(self): assert table_name(self.Building) == 'building' del self.Building.__tablename__ assert table_name(self.Building) == 'building' + + def test_attribute(self): + assert table_name(self.Building.id) == 'building' + assert table_name(self.Building.name) == 'building' + + def test_target(self): + assert table_name(self.Building()) == 'building'