Manually setting the polymorphic type

7 views
Skip to first unread message

NoDamage

unread,
Jul 28, 2009, 8:14:02 PM7/28/09
to sqlalchemy
Is it possible to manually set the type column of a base class when
using single table inheritance? The reason I want to do this is
because I am importing data from an external source which does not
differentiate between the subclass types.

For example:

a_table = Table('a', metadata,
Column('id', Integer, primary_key=True),
Column('type', String(20)),
Column('name', String(20))
)

class A(object): pass
class B(A): pass

a_mapper = mapper(A, a_table, polymorphic_on=a_table.c.type,
polymorphic_identity='a', with_polymorphic='*')
b_mapper = mapper(B, inherits=a_mapper, polymorphic_identity='b')

Here, A is the base class and B is the subclass. I want to be able to
do this:

a = A()
a.type = 'b'

session.add(a)
result = session.query(A).all()

I expect the result to contain an instance of B because I have
explicitly set the type to 'b'. But right now, it looks like because I
have instantiated an instance of A, the type is overwritten as 'a'. Is
there any nice way to do this?

Michael Bayer

unread,
Jul 28, 2009, 11:25:19 PM7/28/09
to sqlal...@googlegroups.com

you could just say:

a.__class__ = B

seems a little weird but it is probably the most "pythonic" way to go.

at the moment the flush() process overwrites the "type" column
regardless of what's in it. Theres no hard reason it has to be that
way, but im hesitant to change it right now within 0.5 since its been
that way for a long time and could break people's applications.

NoDamage

unread,
Jul 29, 2009, 8:37:25 PM7/29/09
to sqlalchemy
That seems easy enough, thanks!
Reply all
Reply to author
Forward
0 new messages