我有许多使用SQLAlchemy的表,以对象的形式建模,这些对象继承自对declarative_base()
的调用结果。例如:
Base = declarative_base()
class Table1(Base):
# __tablename__ & such here
class Table2(Base):
# __tablename__ & such here
等等。我随后想要让一些通用功能对我的每个数据库表类可用,根据文档所述,最简单的方法就是使用多重继承:
Base = declarative_base()
class CommonRoutines(object):
@classmethod
def somecommonaction(cls):
# body here
class Table1(CommonRoutines, Base):
# __tablename__ & such here
class Table2(CommonRoutines, Base):
# __tablename__ & such here
我不喜欢这种方式的原因有三点,A)一般而言,多重继承有些棘手(例如解决像super()
调用等问题),B)如果我添加一张新表格,我必须记得同时从Base
和CommonRoutines
继承,C)实际上,“CommonRoutines”类在某种程度上是一个表格类型。实际上,CommonBase
是一个抽象基类,它定义了一组对所有表格都通用的字段和例程。换句话说:“它是一个”抽象表格“。
所以,我想要的是这样的:
Base = declarative_base()
class AbstractTable(Base):
__metaclass__ = ABCMeta # make into abstract base class
# define common attributes for all tables here, like maybe:
id = Column(Integer, primary_key=True)
@classmethod
def somecommonaction(cls):
# body here
class Table1(AbstractTable):
# __tablename__ & Table1 specific fields here
class Table2(AbstractTable):
# __tablename__ & Table2 specific fields here
但这当然行不通。因为我需要 A) 为 AbstractTable
定义一个 __tablename__
,B) 这个抽象类的特性会带来各种问题,C) 需要指定 AbstractTable
与每个单独表之间的某种数据库关系。
所以我的问题是:有没有可能以合理的方式实现这一点?理想情况下,我想强制执行以下要求:
- 不允许多重继承
CommonBase
/AbstractTable
是抽象的(即不能实例化)
__tablename__
作为错误。 - xsubira