I have a base class which has two subclasses specified via a polymorphic discriminator, and I'm wondering how to set things up so the returned results are instances of the subclass, when I create an instance of the base class and assign the relevant value to the discriminator column. Here's my example code:
import sys from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.attributes import instance_dict from sqlalchemy.orm import relation, backref, class_mapper, create_session e = create_engine('sqlite:////tmp/foo.db', echo=True) Base = declarative_base(bind=e) class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) type = Column(String(12)) name = Column(String(50)) __mapper_args__ = { 'polymorphic_identity': 'base', 'polymorphic_on': type, 'with_polymorphic': '*', } class TestOne(Test): __tablename__ = 'test1' id = Column(Integer, ForeignKey('test.id'), primary_key=True) value1 = Column(String(16)) __mapper_args__ = { 'polymorphic_identity': 'one', } class TestTwo(Test): __tablename__ = 'test2' id = Column(Integer, ForeignKey('test.id'), primary_key=True) value2 = Column(String(16)) __mapper_args__ = { 'polymorphic_identity': 'two', } if __name__ == '__main__': Base.metadata.drop_all() Base.metadata.create_all() session = create_session(bind=e, autocommit=False) test1 = Test(type='one', name='a test') session.add(test1) print test1 This returns an instance of Test, not Test1, despite the discriminator indicating that it should be cast as Test1. Is it possible to handle this in a way which will yield an instance of Test1? Also, if i create test1, and then do session.expunge_all, then immediately requery for session.query(Site).get(1), the returned instance is of type Test1, but trying to set the value for value1 yields 'Can't update table using NULL for primary key value'. Is there a way to fix this, so the necessary table row is created with the same primary key, instead of leaving it blank? It seems that all the info needed to handle the auto-creation of the sub-table is present, but it just fails. Thanks -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To view this discussion on the web visit https://groups.google.com/d/msg/sqlalchemy/-/2GsqHNr52bsJ. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.