2017-02-07 10 views
1

SqlAlchemyを使用して2つのテーブルを作成しようとしていますが、構造は同じですが名前は異なります。同じモデルを使用して2つの異なるテーブルを作成する

表は、この(単純化の例)のようになります。私は、変更すべきだと思うものを、MyTableSecondaryに別の名前を付けるために

Base = declarative_base()  

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

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


class MyTableSecondary(MyTable): 
    pass 

__tablename__(あるいは__table__.name__table__.fullname)です。

しかし、私がそうした場合、それらはすべてクラス属性なので、基本クラスの値も変更します。この制限を一周する

、私はこれらの線に沿って、基本クラスにreturnSecondaryを追加することができます。私はそれを呼び出すとき

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_ 

しかし、それは定義された最初の列にKeyErrorを送出します。

紛失しているものがありますか?あなたがミックスイン

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' 

を作成することができます

答えて

1

は例が示すようにthis example

を参照してください、これも一つのテーブルが他のテーブルが持つ列のスーパーセットを持っている場合に動作します。 その場合、通常通り新しい列を追加するだけです。

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

シンプルで効果的です。あなたはそれを釘付け! – Jir

関連する問題