Jir
Jir

Reputation: 3125

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):
    pass

To give MyTableSecondary a different name, what I think I should change is __tablename__ (or even __table__.name and __table__.fullname).

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 returnSecondary 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,
                  tuple(self.__class__.__bases__),
                  {'__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?

Upvotes: 2

Views: 835

Answers (1)

r-m-n
r-m-n

Reputation: 15090

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

As the example shows, this also works in the case one table has a superset of the columns the other table has. In that case, you just need to add new columns as usual:

class MyTableTertiary(MyTableMixin, Base):
    __tablename__ = 'tertiary_table'
    some_other_col = Column(Integer)

Upvotes: 4

Related Questions