除了表名,我有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))
我可以使用表名作为输入的单个公共表类吗?
答案 0 :(得分:0)
是的,有几种方法可以做到这一点,每种方法都有不同程度的冗长和灵活性:
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")