SQLAlchemy与association_proxy问题的关系

时间:2013-04-17 17:49:08

标签: python sqlalchemy

我一直在浏览许多网站,试图了解正在发生的事情,但我真的需要一些直接的帮助。如果我错过了文档中显而易见的内容,我很抱歉。

这就是我要做的事情(除了基本代码之外,我已经删除了所有内容):

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    login = Column(String(60), primary_key=True, nullable=False)

    groups = association_proxy('user_to_groups', 'group', creator=lambda group: UserToGroup(group_name=group.name))

    def __init__(self, login, groups=None):
        self.login = login
        if groups:
            for group in groups:
                self.groups.append(group)


class Group(Base):
    __tablename__ = 'group'
    name = Column(String(100), primary_key=True, nullable=False)
    description = Column(String(100), nullable=True)

    users = association_proxy('group_to_user', 'user', creator=lambda user: UserToGroup(user_login=user.login))

    def __eq__(self, other):
        return self.name == other.name


class UserToGroup(Base):
    __tablename__ = 'user_to_group'
    user_login = Column(String(60), ForeignKey(User.login), primary_key=true)
    group_name = Column(String(100), ForeignKey(Group.name), primary_key=true)

    user = relationship(User, backref='user_to_groups', cascade='all') #, cascade="all, delete"  #, delete-orphan ?
    group = relationship(Group, backref='group_to_user', cascade='all') #, cascade="all, delete"  #, delete-orphan ?


group1 = Group(name ="g:superadmin")
group2 = Group(name ="g:admin")
session.add_all([group1, group2])
session.flush()
user1 = User(login = "test", groups=[group1, group2])
session.add(user1)
session.flush()


user1 = session.query(User).filter(User.login=='test').one()
print(user1.user_to_groups)
print(type(user1.groups), dir(user1.groups))
user1.groups.remove(Group(name='g:admin'))

这是尝试运行user1.groups.remove(Group(name='g:admin'))后的响应追溯:

  

AssertionError:依赖关系规则尝试在实例'< UserToGroup at 0x7f33f49bd190>'

上清空主键列'user_to_group.user_login'

我想要它只是删除user_to_group表中的行并相应地更新对象以反映更改。

在关系表未映射到对象but I need it to be mapped to an object to use inheritance

之前,我已将其工作

1 个答案:

答案 0 :(得分:3)

级联从拥有父级到被删除的子对象,所以User.user_to_groups,Group.group_to_user:

class UserToGroup(Base):
    __tablename__ = 'user_to_group'
    user_login = Column(String(60), ForeignKey(User.login), primary_key=True)
    group_name = Column(String(100), ForeignKey(Group.name), primary_key=True)

    user = relationship(User, backref=backref('user_to_groups', cascade='all, delete-orphan'))
    group = relationship(Group, backref=backref('group_to_user', cascade='all, delete-orphan'))