Skip to content Skip to sidebar Skip to footer

Get A Polymorphic Subclass Given The Superclass And Polymorphic_identity

If I have sqlalchemy polymorphic subclasses, is there a way to to find a subclass given a superclass and polymorphic_identity? eg: class Employee(Base): __tablename__ = 'emplo

Solution 1:

The base class's mapper has a polymorphic_map property which maps polymorphic identities to their respective mappers, and from there you can get the class. So all you need is:

Employee.__mapper__.polymorphic_map['engineer'].class_

Solution 2:

I have a function in my project that might help you

defmake_class_by_discriminator_dict(module_name, root_cls=object):
    result = {}
    clss = inspect.getmembers(sys.modules[module_name], inspect.isclass)
    for _, cls in clss:
        if cls.__module__ == module_name andissubclass(cls, root_cls):
            try:
                discriminator = cls.__mapper_args__['polymorphic_identity']
                result[discriminator] = cls
            except (AttributeError, KeyError):
                passreturn result

Now what you need is

make_class_by_discriminator_dict(module_name, Employee)['engineer']

Solution 3:

Here's how I did it.

from sqlalchemy.orm import class_mapper
mapping = {}
for mapper inclass_mapper(Employee).polymorphic_iterator():
    mapping[mapper.polymorphic_identity] = mapper

...

# in a from-json function, where app_data["type"] is the discriminator
node_class = mapping[app_data["type"]].class_

Post a Comment for "Get A Polymorphic Subclass Given The Superclass And Polymorphic_identity"