问题
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)
throws:
AssertionError: No such polymorphic_identity 'special' is defined
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.
回答1:
The issue is probably that you have not passed the inheritance information to mapper. When using classical mapping, the inheritance structure is not inferred.
Try something like:
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')
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.
来源:https://stackoverflow.com/questions/44745792/sqlalchemy-polymorphic-inheritance-with-classical-mapping