SQLAlchemy,具有经典映射的多态继承 [英] SQLAlchemy, polymorphic inheritance with classical mapping

查看:60
本文介绍了SQLAlchemy,具有经典映射的多态继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用经典映射而不是声明性映射,在过去的两天里,我试图使继承起作用,我尝试了使用声明性样式,并且它起作用了,但是无论如何,当我尝试使用继承样式时,都无法使它起作用旧的映射样式.

I need to use the classical mapping instead of the declarative, for the last two days I am trying to make inheritance work, I tried with the declarative style and it worked but whatever I tried I cant get it to work when using the old mapping style.

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映射器_args中删除了polymorphic_identity ="normal",则该Item的特殊方法将被调用,似乎SpecializedItem永远不会被视为Item的子级.

If I remove the polymorphic_identity="normal" from the Item mapper_args then the Item's special method gets called, It seems that the SpecialisedItem never gets considered as a child of Item.

推荐答案

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

The issue is probably that you have not passed the inheritance information to mapper. When using classical mapping, the inheritance structure is not inferred.

尝试类似的东西:

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

请注意,无需在映射中为 SpecialisedItem 指定 polymorphic_on .通常,可以推断出基础表之间是否有适当的外键,并且在这里您使用的是同一基础表,因此指向mout.

Note that there is no need to specify polymorphic_on in the mapping for SpecialisedItem. Generally, it will be inferred if there is an appropriate foreign key between the underlying tables, and here you are using the same underlying table so the point is mout.

这篇关于SQLAlchemy,具有经典映射的多态继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆