Sqlalchemy: avoiding multiple inheritance and having abstract base class

前端 未结 3 1987
轻奢々
轻奢々 2020-12-30 02:20

So I have a bunch of tables using SQLAlchemy that are modelled as objects which inherit from the result to a call to declarative_base(). Ie:

Ba         


        
3条回答
  •  半阙折子戏
    2020-12-30 02:50

    SQLAlchemy version 0.7.3 introduced the __abstract__ directive which is used for abstract classes that should not be mapped to a database table, even though they are subclasses of sqlalchemy.ext.declarative.api.Base. So now you create a base class like this:

    Base = declarative_base()
    
    class CommonRoutines(Base):
        __abstract__ = True
    
        id = Column(Integer, primary_key=True)
    
        def __init__(self):
            # ...
    

    Notice how CommonRoutines doesn't have a __tablename__ attribute. Then create subclasses like this:

    class Foo(CommonRoutines):
        __tablename__ = 'foo'
    
        name = Column(...)
    
        def __init__(self, name):
            super().__init__()
            self.name = name
            # ...
    

    This will map to the table foo and inherit the id attribute from CommonRoutines.

    Source and more information: http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/declarative.html#abstract

提交回复
热议问题