【问题标题】:Sqlalchemy : association table for many-to-many relationship between groups and members. How can I delete a relationship?Sqlalchemy:组和成员之间多对多关系的关联表。如何删除关系?
【发布时间】:2012-11-21 20:57:57
【问题描述】:

我已经设置了这些表格: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')
...

我正在尝试删除一个用户和他的组之一之间的关系,但我真的想不出一个可以做到这一点的查询。使用 Sqlalchemy 有什么方法可以做到这一点?

感谢您的宝贵时间。

【问题讨论】:

    标签: sqlalchemy pylons


    【解决方案1】:

    您的意思是要从组中删除用户?

    # 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()
    

    【讨论】:

      猜你喜欢
      • 2017-10-30
      • 1970-01-01
      • 2015-08-05
      • 2015-03-16
      • 1970-01-01
      • 2011-04-22
      • 2023-03-17
      • 2023-01-27
      相关资源
      最近更新 更多