thanks for sending a nice, succinct example...very rare these days.   Use this:

class GroupClient(Base):
   __tablename__ = 'clientgroup'
   
   client_id = Column('client_id', Integer, ForeignKey('client.id'),primary_key 
= True)
   group_id = Column('group_id', Integer, ForeignKey('group.id'), primary_key = 
True)
   client = relation(Client, backref = backref('client_group', cascade='all, 
delete-orphan'))
   group = relation(Group, backref = backref('client_group'))




On Jul 28, 2010, at 9:00 AM, DimonB wrote:

> from sqlalchemy import *
> from sqlalchemy.ext.declarative import declarative_base,
> DeclarativeMeta
> from sqlalchemy.ext.associationproxy import association_proxy
> from sqlalchemy.orm import scoped_session, sessionmaker, relation,
> backref
> 
> engine = create_engine('sqlite://')
> meta = MetaData()
> meta.bind = engine
> 
> class Base(declarative_base(metadata=meta)):
>    _decl_class_registry = {}
>    def __init__(self, *args, **kwargs):
>        for key, val in kwargs.iteritems():
>            self.__setattr__(key, val)
> 
> class Client(Base):
>    __tablename__ = 'client'
>    id = Column('id', Integer, primary_key=True)
>    name = Column('name', String(50))
>    groups = association_proxy('client_group', 'group', creator=lambda
> x: ClientGroup(client=x))
> 
> class Group(Base):
>    __tablename__ = 'group'
>    id = Column('id', Integer, primary_key=True)
>    name = Column('name', String(50))
>    clients = association_proxy('client_group', 'client',
> creator=lambda x: GroupClient(client=x))
> 
> class GroupClient(Base):
>    __tablename__ = 'clientgroup'
>    client_id = Column('client_id', Integer, ForeignKey('client.id'),
> primary_key = True)
>    group_id = Column('group_id', Integer, ForeignKey('group.id'),
> primary_key = True)
>    client = relation(Client, backref = backref('client_group'))
>    group = relation(Group, backref = backref('client_group'))
> 
> meta.create_all()
> 
> session = scoped_session(sessionmaker(bind=engine))
> 
> clnt = Client(name='test')
> session.add(clnt)
> grp = Group(name='tg')
> session.add(grp)
> 
> grp.clients.append(clnt)
> 
> #session.flush()
> 
> 
> #grp.clients.remove(clnt)
> clnt.groups.remove(grp)
> session.flush()

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" 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/sqlalchemy?hl=en.

Reply via email to