Skip to content

Commit 4a7a218

Browse files
committed
Fixed bug when using a declarative function for the __tablename__
When specifying a function to dynamically define a tablename as a declared attribute it became impossible to overwrite it using a manually defined name. Look at the test to see the issue, with the original code this test would fail.
1 parent 1a48cc5 commit 4a7a218

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

gino/declarative.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,9 @@ def _init_table(cls, sub_cls):
166166
updates[k] = sub_cls.__attr_factory__(k, v)
167167
elif isinstance(v, (sa.Index, sa.Constraint)):
168168
inspected_args.append(v)
169-
if table_name is None:
170-
table_name = getattr(sub_cls, '__tablename__', None)
169+
if getattr(sub_cls, '__tablename__', None) and \
170+
not callable(getattr(sub_cls, '__tablename__')):
171+
table_name = getattr(sub_cls, '__tablename__')
171172
if table_name is None:
172173
return
173174
sub_cls._column_name_map = column_name_map

tests/test_declarative.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,20 @@ class Model(db.Model):
260260
select_col = db.Column(name=db.quoted_name('select', False))
261261
assert select_col.name == 'select'
262262
assert not select_col.name.quote
263+
264+
265+
async def test_overwrite_declared_table_name():
266+
class MyTableNameMixin:
267+
@db.declared_attr
268+
def __tablename__(cls):
269+
return cls.__name__.lower()
270+
271+
class MyTableWithoutName(MyTableNameMixin, db.Model):
272+
id = db.Column(db.Integer, primary_key=True)
273+
274+
class MyTableWithName(MyTableNameMixin, db.Model):
275+
__tablename__ = 'manually_overwritten_name'
276+
id = db.Column(db.Integer, primary_key=True)
277+
278+
assert MyTableWithoutName.__table__.name == 'mytablewithoutname'
279+
assert MyTableWithName.__table__.name == 'manually_overwritten_name'

0 commit comments

Comments
 (0)