Hi all,
I'm just getting my feet wet with SQLAlchemy and was having trouble
getting polymorphic inheritance to work... so after a little messing
around I came up with this simple model.py...
I'd just like to share this and see if somebody has a better way
before trying to post it on the docs site...
from datetime import datetime
from turbogears.database import metadata, session
from sqlalchemy import *
from sqlalchemy.ext.activemapper import ActiveMapper, column, \
one_to_many, one_to_one,
many_to_many
from sqlalchemy.ext.assignmapper import assign_mapper
class Person(ActiveMapper):
class mapping:
__table__ = 'person'
person_id = column(Integer, primary_key=True)
name = column(Unicode)
poly = column(Unicode(30))
class Jerk(Person):
class mapping:
__table__ = 'jerk'
jerk_id = column(Integer, foreign_key='person.person_id',
primary_key=True)
smelly = column(Boolean, default=False)
def __init__(self, *args, **kwargs):
"""Hack to make polymorphic inheritance work.
Only needed on inherited classes."""
super(Jerk, self ).__init__(*args,**kwargs)
self.poly = 'jerk'
person_table = Person.table
jerk_table = Jerk.table
people_join = polymorphic_union(
{
'jerk' : Person.table.join(Jerk.table),
'person' : person_table.select(person_table.c.poly == 'person')
}, None, 'pjoin'
)
person_mapper = class_mapper(Person)
person_mapper.select_table = people_join
person_mapper.polymorphic_on = people_join.c.poly
person_mapper.polymorphic_identity = 'person'
jerk_mapper = class_mapper(Jerk)
jerk_mapper.polymorphic_identity = 'jerk' # leave this in case it's
fixed later
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---