Sqlalchemy:避免多重继承并具有抽象基类

Ada*_*kin 16 python sqlalchemy multiple-inheritance

所以我有一堆使用SQLAlchemy的表,它们被建模为从结果继承到调用的对象declarative_base().即:

Base = declarative_base()
class Table1(Base):
    # __tablename__ & such here

class Table2(Base):
     # __tablename__ & such here
Run Code Online (Sandbox Code Playgroud)

等等.然后,我想为每个数据库表类提供一些常用功能,根据文档执行此操作的最简单方法是执行多重继承:

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
Run Code Online (Sandbox Code Playgroud)

我不喜欢这件事是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
Run Code Online (Sandbox Code Playgroud)

但这当然不起作用,因为我必须A)定义一个__tablename__for AbstractTable,B)事物的ABC方面会引起各种令人头疼的问题,而且C)必须在AbstractTable每个表之间指出某种DB关系.

所以我的问题是:是否有可能以合理的方式实现这一目标?理想情况下,我想强制执行:

  • 没有多重继承
  • CommonBase/ AbstractTable是抽象的(即无法实例化)

Ant*_*son 33

SQLAlchemy版本0.7.3引入了该__abstract__指令,该指令用于不应映射到数据库表的抽象类,即使它们是sqlalchemy.ext.declarative.api.Base的子类.所以现在你创建一个这样的基类:

Base = declarative_base()

class CommonRoutines(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True)

    def __init__(self):
        # ...
Run Code Online (Sandbox Code Playgroud)

请注意CommonRoutines没有__tablename__属性.然后像这样创建子类:

class Foo(CommonRoutines):
    __tablename__ = 'foo'

    name = Column(...)

    def __init__(self, name):
        super().__init__()
        self.name = name
        # ...
Run Code Online (Sandbox Code Playgroud)

这将映射到表fooid从中继承属性CommonRoutines.

来源和更多信息:http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/declarative.html#abstract


van*_*van 16

它非常直接,您只需declarative_base()返回一个Base继承自您的CommonBaseusing cls=参数的类.也在扩充基础文档中显示.您的代码可能看起来类似于下面的代码:

class CommonBase(object):
    @classmethod
    def somecommonaction(cls):
        # body here

Base = declarative_base(cls=CommonBase)

class Table1(Base):
    # __tablename__ & Table1 specific fields here

class Table2(Base):
     # __tablename__ & Table2 specific fields here
Run Code Online (Sandbox Code Playgroud)