SQLAlchemy继承和父表的属性组合

时间:2016-01-21 21:49:19

标签: python 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,
                ...
                }

我发现自己在每个测试类型的status函数中重复了常见属性(例如iddateget_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 个答案:

答案 0 :(得分: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