Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy - double polymorphic inheritance problem

I've got a class mapping with two polymorphic inheritance :

#test classes

class AbstractA(Base):

    __tablename__ = "abstract_a"

    id = Column(Integer, primary_key=True)
    class_name = Column('class_name', String(50))

    __mapper_args__ = {
      'polymorphic_on': class_name,
    }


#some stuff here

class AbstractB(AbstractA):

    __tablename__ = "abstract_b"

    id = Column(Integer, ForeignKey('abstract_a.id'), primary_key=True)
    class_name = Column('class_name', String(50))

    __mapper_args__ = {
      'polymorphic_on': class_name,
      'polymorphic_identity': __tablename__,
    }

#some stuff here

class ClassA(AbstractB):

    __tablename__ = "table_a"
    __mapper_args__ = {
      'polymorphic_identity': __tablename__,
    }

    id = Column(Integer, ForeignKey('abstract_b.id'), primary_key=True)
    label = Column('label', String(50))

    def __init__(self, label):
        self.label = label

I persist a ClassA object :

object = ClassA('toto')
db_session.add(object)
db_session.commit()

When I try to reload the object like this :

reloaded_object = AbstractB.query.first()

I get back a ClassA object (just fine)

but when I try to reload like this :

reloaded_object = AbstractA.query.first()

I get back a AbstractA object because abstract_a.class_name has not been set to polymorphic_identity.

Is this an issue or expected work?

like image 206
jean-phi Avatar asked Sep 25 '26 12:09

jean-phi


1 Answers

Why do you need another discriminator for AbstractB subclasses instead of using single AbstractA.class_name for the whole inheritance tree? Just remove 2 lines from AbstractB definition and your test will work:

class AbstractB(AbstractA):

    __tablename__ = "abstract_b"

    id = Column(ForeignKey('abstract_a.id'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
    }
like image 199
Denis Otkidach Avatar answered Sep 28 '26 08:09

Denis Otkidach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!