Jir Jir - 4 years ago 87
Python Question

Create two different tables using the same model

I'm trying to create two tables using SqlAlchemy, identical to each other in terms of structure, but with different names.

The tables look like this (simplified example):

Base = declarative_base()

class MyTable(Base, OperationsMixin):
__tablename__ = 'the_table_name'

colA = Column(BigInteger)
colB = Column(TIMESTAMP(timezone=True))

class MyTableSecondary(MyTable):

To give MyTableSecondary a different name, what I think I should change is
(or even

However, if I do so, I'll change the values for the base class as well, since all those are class attributes.

To go around this limitation, I could add a
to the base class along these lines:

def returnSecondary(self, suffix):
tableArgs = list(self.__table_args__)
for a in tableArgs:
a.name += suffix

classname = self.__class__.__name__ + 'Secondary'
class_ = type(classname,
{'__tablename__': self.__tablename__ + suffix,
'__table_args__': tuple(self.__table_args__)})

return class_

However, when I call it, it raises a KeyError for the first column defined.

Is there something I'm missing?

Answer Source

You can create mixin

class MyTableMixin(object):
    colA = Column(BigInteger)
    colB = Column(TIMESTAMP(timezone=True))

class MyTable(MyTableMixin, Base):
    __tablename__ = 'the_table_name'

class MyTableSecondary(MyTableMixin, Base):
    __tablename__ = 'secondary_table'

see this example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download