2016-01-21 86 views
0

我有像下面SQLAlchemy的繼承和

class HasId(object): 

    @declared_attr 
    def id(cls): 
     return Column('id', Integer, Sequence('test_id_seq'), primary_key=True) 

    @declared_attr 
    def status(cls): 
     return Column('status', String(20)) 

    @declared_attr 
    def date(cls): 
     return Column('date', DateTime) 

    ... 



class TestParent(HasId, Model): 
    __tablename__ = 'tests' 

    discriminator = Column(String(50)) 

    __mapper_args__ = {'polymorphic_on': discriminator} 

    <all columns for the 'tests' table defined in class 'Has ID' above> 

    def __init__(self, **kwargs): 
     super(TestParent, self).__init__(**kwargs) 




class FooTest(TestParent, Model): 
    __tablename__ = 'footests' 
    __mapper_args__ = {'polymorphic_identity': 'footests'} 

    id = Column(Integer, ForeignKey('tests.id'), primary_key=True) 
    pressure_start = Column(Float) 
    ... 

    def __init__(self, **kwargs): 
     super(FooTest, self).__init__(**kwargs) 

    def get_json(self): 
     return {'id': id, 
       'discriminator': self.discriminator, ///// PULL discriminator FROM TestParent 
       'date': date,      ///// PULL date FROM TestParent    
       'status': self.status,    ///// PULL status FROM TestParent    
       'pressure_start': self.pressure_start, 
       ... 
       } 

,我發現自己在每種測試類型的重複的共同屬性(比如statusiddate ...)定義的數據模型父表的性能組合get_json()功能。

如何才能使其僅定義屬於該模型中的繼承模型的屬性,並定義父模型中所有模型共有的屬性?

我想是這樣的僞代碼如下

class TestParent(HasId, Model): 

    ... 

    def parent_json(): 
     return {'status': self.status, 
       'date': self.date 
       ...} 

class FooTest(TestParent, Model): 

    ... 

    def get_json(): 

     myjson = {'pressure_start': self.pressure_start, 
        ...} 

     test_json = parent_json + my_json 

     return test_json 

回答

1

使用super對父模型訪問方法。

class FooTest(TestParent, Model): 

    ... 

    def get_json(self): 

     my_json = {'pressure_start': self.pressure_start, 
        ...} 
     parent_json = super(FooTest, self).parent_json() 
     my_json.update(parent_json) 

     return my_json