2016-01-21 66 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