SQLAlchemy,经典映射的多态性继承

SQLAlchemy,经典映射的多态性继承,sqlalchemy,flask-sqlalchemy,Sqlalchemy,Flask Sqlalchemy,我需要使用经典映射而不是声明式,在过去的两天里,我一直在努力使继承工作,我尝试使用声明式样式,但无论我尝试了什么,当使用旧的映射样式时,我都无法让它工作 class Item(object): def specialised_method(self): return "I am not special" class SpecialisedItem(Item): __mapper_args__ = { 'polymorphic_identity

我需要使用经典映射而不是声明式,在过去的两天里,我一直在努力使继承工作,我尝试使用声明式样式,但无论我尝试了什么,当使用旧的映射样式时,我都无法让它工作

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参数中删除多态性_identity=“normal”,则会调用Item的特殊方法,似乎SpecializedItem从未被视为Item的子项。

问题可能是您没有将继承信息传递给
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')

请注意,无需在
specializedItem
的映射中指定
polymorphic\u on
。通常,将推断基础表之间是否存在适当的外键,并且这里您使用的是相同的基础表,因此点是mout。

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

尝试以下方法:

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')

请注意,无需在
specializedItem
的映射中指定
polymorphic\u on
。通常,将推断基础表之间是否存在适当的外键,这里您使用的是相同的基础表,因此重点是mout。

谢谢。。。这可能是我的文档阅读技能,但我认为sqlalchemy在使用非声明性样式时缺少文档。你的代码有效。谢谢你。。。这可能是我的文档阅读技能,但我认为sqlalchemy在使用非声明性样式时缺少文档。你的代码可以工作。