2009-09-23 45 views
2

我有这些表的设置:http://pastie.org/627764Sqlalchemy:组与会员之间多对多关系的关联表。我如何删除关系?

...  
    # This is the association table for the many-to-many relationship between 
    # groups and members - this is, the memberships. 
    user_group_table = Table('user_group', metadata, 
     Column('user_name', Integer, ForeignKey('user.user_name', 
      onupdate="CASCADE", ondelete="CASCADE")), 
     Column('group_name', Integer, ForeignKey('group.group_name', 
      onupdate="CASCADE", ondelete="CASCADE")) 
    ) 

    class Group(DeclarativeBase): 

     __tablename__ = 'group' 

     group_name = Column(Unicode(16), primary_key=True) 

     users = relation('User', secondary=user_group_table, backref='groups') 
... 

我想删除一个用户和他的团队之一之间的关系,但我真的不能拿出,做它的查询。任何方式使用Sqlalchemy做到这一点?

谢谢你的时间。

回答

3

你的意思是你想从一个组中删除一个用户?

# fetch the mapped classes 
group = Session.query(Group).some_filters().one() 
user = Session.query(User).some_filters().one() 

# group.users is a list of all users in this group 
# remove one and it will be removed from the DB 
group.users.remove(user) 
Session.commit() 
相关问题