15 May 17:21
Polymorphic across foreign key
From: J. Cliff Dyer <jcd <at> sdf.lonestar.org>
Subject: Polymorphic across foreign key
Newsgroups: gmane.comp.python.sqlalchemy.user
Date: 2008-05-15 15:24:55 GMT
Subject: Polymorphic across foreign key
Newsgroups: gmane.comp.python.sqlalchemy.user
Date: 2008-05-15 15:24:55 GMT
I'm trying to implement polymorphic inheritance using the
sqlalchemy.ext.declarative, but the field that I want to use for the
polymorphic_on is not in my polymorphic base table, but at the other end
of a many-to-one relationship. We have items of many types, and in the
item table, we have a type_id field which contains an integer, but in
the item_type table, that integer is mapped to a descriptive name.
Essentially, I'd like to use that name as my polymorphic_identity. I've
tried to implement this with declarative classes below, but I get an
error, also shown below.
class ItemType(Declarative):
__table__ = sa.Table('item_type', Declarative.metadata)
type_id = sa.Column('type_id', sa.Integer, primary_key=True)
description = sa.Column('description', sa.Unicode(250))
item = orm.relation('Item', backref='item_type')
class Item(Declarative):
__table__ = sa.Table('item', Declarative.metadata)
item_id = sa.Column('item_id', sa.Integer, primary_key=True)
type_id = sa.Column('type_id', sa.Integer,
sa.ForeignKey('item_type.type_id'))
short_title = sa.Column('short_title', sa.Unicode(100))
__mapper_args__ = {'polymorphic_on': ItemType.description }
### Traceback follows:
"""
Traceback (most recent call last):
File "polymorph_test.py", line 23, in ?
(Continue reading)
RSS Feed