On Oct 16, 7:42 pm, Michael Bayer <[EMAIL PROTECTED]> wrote:
> On Oct 16, 2007, at 1:30 PM, [EMAIL PROTECTED] wrote:
> > Am I really supposed to save/flush/clear/query my objects to get the
> > correct mappings?
> > Or is this a bug?
>
> the advised pattern here is the
> "association object" pattern described in the docs:  
> http://www.sqlalchemy.org/docs/04/
> mappers.html#advdatamapping_relation_patterns_association

Ah, great. Thank you for your advice!

Using the association proxy 
http://www.sqlalchemy.org/docs/04/plugins.html#plugins_associationproxy
I can also easily access the entities without explicitly using the
association:

u1 = User("test user 1")
e1 = Event("test event 1")
u1.events.append(e1) # association automatically created

u2 = User("test user 2")
e2 = Event("test event 2")
p2 = Participation(user=u2, event=e2, status=42) # explicit creation
of the association

Modified code for classes and mappers:

from sqlalchemy.ext.associationproxy import association_proxy

class User(object):
    def __init__(self, name=None):
        self.name = name
    events = association_proxy('participations', 'event',
creator=lambda e: Participation(event=e))

class Event(object):
    def __init__(self, title=None):
        self.title = title
    users = association_proxy('participations', 'user', creator=lambda
u: Participation(user=u))

class Participation(object):
    def __init__(self, event=None, user=None, status=0):
        self.event = event
        self.user = user
        self.status = status

mapper(User, user_table,
    properties=dict(
        participations=relation(Participation, backref='user'),
    )
)

mapper(Participation, participation_table,
    properties=dict(
        user=relation(User, backref='participations')
    )
)

mapper(Event, event_table,
    properties=dict(
        participations=relation(Participation, backref='event'),
    )
)


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to