Sqlalchemy: link table for many-to-many relationships between groups and members. How can I delete a relationship?
I have the settings for these tables: http://pastie.org/627764
...
# 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')
...
I'm trying to remove the association between one user and one of their group, but I can't really find the query that does this. Any way to do this with Sqlalchemy?
Thank you for your time.
+2
source to share
1 answer
Do you want to remove a user from a group?
# 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()
+3
source to share