It seems that when setting specific attributes inside the _init_ of an ORM model, it's not initialized when the model gets queried and get lost.
Should the attributes be set inside the class instead of the _init_ method?
This is the code:
class User(Base):
__tablename__ = 'user'
name = Column(sqlalchemy.String, primary_key=True)
type = sqlalchemy.Column(sqlalchemy.String, nullable=False)
__mapper_args__ = {'polymorphic_on': type, 'polymorphic_identity': 'user'}
def __init__(self, name):
self.name = name
self.some_attribute = "test"
class SpecialUser(User):
__mapper_args__ = {'polymorphic_identity': 'suser'}
why_special = Column(String(64))
def __init__(self, name, why_special):
super(SpecialUser, self).__init__(name)
self.why_special = why_special
s = SpecialUser("a", "a")
session.add(s)
session.commit()
model = sqlalchemy.orm.with_polymorphic(User, "*")
su = session.query(model).first()
session.expunge_all()
print(s.some_attribute)
print(su.some_attribute)
output:
test
Traceback (most recent call last):
File "./test.py", line 28, in main
print(su.some_attribute)
AttributeError: 'SpecialUser' object has no attribute 'some_attribute'
What is the best solution for this issue?