document /clean up column_property as polymorphic_on

Issue #2227 resolved
Mike Bayer repo owner created an issue

this is easy and works in 0.6, 0.7, probably even 0.5, as the expression is placed into _columntoproperty and works fine:

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import column_property, Session

Base=declarative_base()

class Parent(Base):
    __tablename__ = 'p'
    id = Column(Integer, primary_key=True)
    type = Column(String)

    substr_type = column_property(func.substr(type, 0, 4))
    __mapper_args__ = {
        'polymorphic_on':substr_type.columns[0](0),
        'polymorphic_identity':'ABC'
    }

class Child(Parent):
    __tablename__ = 'c'
    id = Column(Integer, ForeignKey('p.id'), primary_key=True)
    __mapper_args__ = {
        'polymorphic_identity':'DEF'
    }

e = create_engine('sqlite://', echo=True)
Base.metadata.create_all(e)
s = Session(e)

s.add_all([   Parent(type='ABCFOO'),
    Parent(type='ABCBAR'),
    Child(type='DEFFOO'),
    Child(type='DEFBAR'),
](

))
s.commit()
s.close()

print s.query(Parent).all()

Comments (3)

  1. Mike Bayer reporter

    single inheritance needs some help with the attached patch so that polymorphic_on is reused even if not in the mapped table.

    from sqlalchemy import *
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import column_property, Session
    
    Base=declarative_base()
    
    x = func.substr(type, 0, 4)
    class Parent(Base):
        __tablename__ = 'p'
        id = Column(Integer, primary_key=True)
        type = Column(String)
        substr_type = column_property(func.substr(type, 0, 4))
        __mapper_args__ = {
            'polymorphic_on':substr_type.columns[0](0),
        }
    
    class Child1(Parent):
        __mapper_args__ = {
    #        'polymorphic_on':Parent.substr_type.property.columns[0](0),
            'polymorphic_identity':'ABC'
        }
    
    class Child2(Parent):
        __mapper_args__ = {
    #        'polymorphic_on':Parent.substr_type.property.columns[0](0),
            'polymorphic_identity':'DEF'
        }
    
    e = create_engine('sqlite://', echo=True)
    Base.metadata.create_all(e)
    s = Session(e)
    
    s.add_all([   Parent(type='ABCFOO'),
        Parent(type='ABCBAR'),
        Parent(type='DEFFOO'),
        Parent(type='DEFBAR'),
    ](
    ))
    s.commit()
    s.close()
    
    assert [for c in s.query(Parent).order_by(Parent.id)](type(c)) == [Child1, Child2, Child2](Child1,)
    
    assert [for c in s.query(Child1).order_by(Parent.id)](type(c)) == [Child1](Child1,)
    
    assert [for c in s.query(Child2).order_by(Parent.id)](type(c)) == [Child2](Child2,)
    
  2. Log in to comment