I just got really confused.  I have code that does 
...join(schema.MappedClass.relation), and it works.  But I had other code 
that did foo = schema.MappedClass.relation, and it didn't work because 
'relation' wasn't there.

The fix is to call orm.configure_mappers(), which happens by magic at 
various points.  Perhaps mapped classes should have a __getattr__ that 
calls configure_mappers.

Here's some example code along with the rather evil hack that I used to 
figure this out (I couldn't find it in the docs anywhere).

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


#!/usr/bin/python

from sqlalchemy import *
from sqlalchemy import orm
import sqlalchemy as sa
import sqlalchemy.events
import traceback

metadata = sa.MetaData()

group = sa.Table(
    'group', metadata,
    Column('group_id', Integer, primary_key=True),
    )

# This can be ignored other than for debugging.
class MetaHack(type):
    def __init__(cls, name, bases, dct):
        super(MetaHack, cls).__init__(name, bases, dct)
    def __setattr__(self, attr, val):
#        print 'Setting %s = %r' % (attr, val)
#        traceback.print_stack()
        type.__setattr__(self, attr, val)

class Group(object):
    __metaclass__ = MetaHack

sa.orm.mapper(Group, group)

thing = sa.Table(
    'thing', metadata,
    Column('thing_id', Integer, primary_key=True),
    Column('group_id', Integer, ForeignKey('group.group_id')),
    )

class Thing(object):
    pass

sa.orm.mapper(Thing, thing, properties={'group' : orm.relationship(Group, backref='things')})

try:
    Group.things
except AttributeError, e:
    print 'First try: %s' % e

orm.configure_mappers()

# This would also work...
#e = sa.create_engine('sqlite:///:memory:')
#s = sa.orm.create_session(bind=e)
#s.query(Group)

Group.things
print 'Now it worked'

Reply via email to