To avoid writing a function selecting the correct class for a 'type' value, I would like to create models using the parent class ('Employee') and 'type' instead of using the child class ('Manager', 'Engineer') in the first place. I noticed that the resulting object is not of the respecting child class (e.g. 'Manager'), even after re-querying it with the child class or with with_polymorphic. However, only in a new session this works out. Is there a way to achieve this without opening a new session?
Here is my example script - I am using sqlalchemy version 1.4.37:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import declarative_base, \
relationship, sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Employee(Base):
__tablename__ = "employee"
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(50))
__mapper_args__ = {
"polymorphic_identity": "employee",
"polymorphic_on": type,
'with_polymorphic': '*'
}
class Manager(Employee):
manager_data = Column(String(50))
__mapper_args__ = {
"polymorphic_identity": "manager"
}
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
manager = Employee(name='name of Manager', type='manager')
session.add(manager)
session.flush()
manager_id =
manager.idsession.commit()
# doesn't work:
m0 = session.query(Employee).filter_by(id=manager_id).first()
print(">>", m0.__mapper_args__['polymorphic_identity'])
try:
print(m0.manager_data)
except:
print(">> didn't work")
# doesn't work:
m = session.query(Manager).filter_by(id=manager_id).first()
print(">>", m.__mapper_args__['polymorphic_identity'])
try:
print(m.manager_data)
except:
print(">> didn't work")
# works:
session.close()
session2 = Session()
m1 = session2.query(Employee).filter_by(id=manager_id).first()
print(">>", m1.__mapper_args__['polymorphic_identity'])
print(m1.manager_data)
# works:
m = session2.query(Manager).filter_by(id=manager_id).first()
print(">>", m.__mapper_args__['polymorphic_identity'])
print(m.manager_data)
session2.close()
Thanks,
David