'NoForeignKeysError when using polymorphic_load, classic/imperative mapping, single table inheritance

I can't seem to get polymorphic_load to work when using classic/primitive mapping and single table inheritance. Things work fine when using declarative mapping.

Using the following classic/primitive mapping config

ThingTable = Table(
    'thing', mapper_registry.metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('name', String(50)),
    Column('type', String(20))
)


class GenericThing:
    def __init__(self, name, type):
        self.id = None
        self.name = name
        self.type = type


class SpecificThing(GenericThing):
    pass


mapper_registry.map_imperatively(
    GenericThing,
    ThingTable,
    polymorphic_on=ThingTable.c.type,
    with_polymorphic='*',
    polymorphic_identity='generic'
)

mapper_registry.map_imperatively(
    SpecificThing,
    ThingTable,
    inherits=GenericThing,
    polymorphic_load='inline',
    polymorphic_identity='specific'
)

I add a record to the thing table with type set to specific.

When I query using GenericThing to get all the specific things I get a NoForeignKeysError (same issue if I don't filter_by as well).

session.query(GenericThing).filter_by(type='specific')
Traceback (most recent call last):
<SNIP>
    raise exc.NoForeignKeysError(
sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'thing' and 'thing'.

Given it's the same table I'm not sure why it's looking for a ForeignKey.

But it works fine when I use SpecificThing.

session.query(SpecificThing).filter_by(type='specific').all()
[<__main__.SpecificThing object at 0x7effdf4879a0>]

I am able to use GenericThing to get all the things when I set up using the declarative method.

Is this possible to do using classical mapping?

SQLAlchemy==1.4.32



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source