Sqlalchemy: avoiding multiple inheritance and having abstract base class

前端 未结 3 1964
轻奢々
轻奢々 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:46

    It is pretty straigh-forward, you just make declarative_base() to return a Base class which inherits from your CommonBase using cls= parameter. Also shown in Augmenting The Base docs. Your code might then look similar to below:

    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
    

提交回复
热议问题