在sqlalchemy中,如何仅使用表名快速定义相同的表模型(calss)是不同的?

时间:2016-03-02 06:28:18

标签: python mysql sqlalchemy

除了表名,我有10个表完全相同。而且我不想将10个表合并为一个。现在我尝试使用sqlalchemy将数据插入这些表中。我发现我在代码中重复执行以下操作:

class tableA(DeclarativeBase):
    __tablename__ = "A"
    id = Column(Integer, primary_key=True)
    title = Column('title', String(200))
    link = Column('link', String(200))

class tableB(DeclarativeBase):
    __tablename__ = "B"
    id = Column(Integer, primary_key=True)
    title = Column('title', String(200))
    link = Column('link', String(200))
    ......
    ......
class tableH(DeclarativeBase):
    __tablename__ = "H"
    id = Column(Integer, primary_key=True)
    title = Column('title', String(200))
    link = Column('link', String(200))

我可以使用表名作为输入的单个公共表类吗?

1 个答案:

答案 0 :(得分:0)

是的,有几种方法可以做到这一点,每种方法都有不同程度的冗长和灵活性:

Common Base Class

class Foo(DeclarativeBase):
    __abstract__ = True
    id = Column(Integer, primary_key=True)
    title = Column('title', String(200))
    link = Column('link', String(200))

class tableA(Foo):
    __tablename__ = "A"

密新

class Foo(object):
    id = Column(Integer, primary_key=True)
    title = Column('title', String(200))
    link = Column('link', String(200))

class tableA(Foo, DeclarativeBase):
    __tablename__ = "A"

动态type

def create_table(name):
    return type("table" + name, (DeclarativeBase,), {
        "__tablename__": name,
        "id": Column(Integer, primary_key=True),
        "title": Column('title', String(200)),
        "link": Column('link', String(200)),
    })

tableA = create_table("A")