SQLAlchemy,具有经典映射的多态继承

时间:2017-06-25 11:14:32

标签: sqlalchemy flask-sqlalchemy

我需要使用经典映射而不是声明,在最近两天我尝试继承工作,我尝试使用声明式样式并且它工作但是无论我尝试了什么我都不能让它在使用时工作旧的绘图风格。

class Item(object):

    def specialised_method(self):
        return "I am not special"


class SpecialisedItem(Item):
    __mapper_args__ = {
        'polymorphic_identity': 'special',
    }

    def specialised_method(self):
        return "I am special"

orm.mapper(Item, enviroment.tables.items,
           polymorphic_on=enviroment.tables.items.c.type,
           polymorphic_identity="normal")


# orm.mapper(SpecialisedItem, enviroment.tables.items,polymorphic_on=enviroment.tables.items.c.type,polymorphic_identity='special')

def test_inheritance(request):
    enviroment=get_enviroment()
    session=enviroment.session
    for item in session.query(Item).filter_by(type="special"):
        print(item.type,item.specialised_method(),item)

抛出:

AssertionError: No such polymorphic_identity 'special' is defined

如果我从Item mapper_args中删除了polymorphic_identity =“normal”,则会调用Item的特殊方法,似乎SpecialisedItem永远不会被视为Item的子级。

1 个答案:

答案 0 :(得分:3)

问题可能是您没有将继承信息传递给mapper。使用经典映射时,不会推断继承结构

尝试类似:

class Item(object):
    def specialised_method(self):
        return "I am not special"

class SpecialisedItem(Item):
    def specialised_method(self):
        return "I am special"

orm.mapper(Item, enviroment.tables.items,
           polymorphic_on=enviroment.tables.items.c.type,
           polymorphic_identity="normal")

orm.mapper(SpecialisedItem,
           enviroment.tables.items,

           # you need to specify the parent
           inherits=Item,
           polymorphic_identity='special')

请注意,无需在polymorphic_on的映射中指定SpecialisedItem。通常,如果在基础表之间存在适当的外键,并且在这里使用相同的基础表,那么该点将是mout。