I have a class inheritance scheme as layed out in http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
type = Column(String)
__mapper_args__ = {'polymorphic_on': type}
class Child(Parent):
__tablename__ = 'child'
id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity': 'child'}
I'd like to be able to create an instance of Child using the constructor of Parent (like Parent(type='child')) but it doesn't work. When I fire up IPython...
In [1]: from stackoverflow.question import Parent, Child
In [2]: from sqlalchemy import create_engine
In [3]: from sqlalchemy.orm import sessionmaker
In [4]: session = sessionmaker(bind=create_engine(...), autocommit=True)()
In [5]: with session.begin():
p = Parent(type='child')
session.add(p)
...:
/.../lib/python3.4/site-packages/sqlalchemy/orm/persistence.py:155: SAWarning: Flushing object <Parent at 0x7fe498378e10> with incompatible polymorphic identity 'child'; the object may not refresh and/or load correctly
mapper._validate_polymorphic_identity(mapper, state, dict_)
In [6]: session.query(Parent).all()
Out[6]: [<stackoverflow.question.Parent at 0x7fe498378e10>]
In [7]: session.query(Child).all()
Out[7]: []
Is this possible? Is it a good idea?