3

I've been wading through many website to try to understand what's going on, but I really need some direct help. I'm sorry if I missed something obvious in the docs.

Here's what I'm trying to do (I've cut out everything but the essential code):

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'))

And here's the response traceback after trying to run user1.groups.remove(Group(name='g:admin')):

AssertionError: Dependency rule tried to blank-out primary key column 'user_to_group.user_login' on instance '<UserToGroup at 0x7f33f49bd190>'

What I want it to do is simply delete the row in the user_to_group table and update the objects accordingly to reflect the change.

I had it working before when the relationship table wasn't mapped to an object, but I need it to be mapped to an object to use inheritance

4

1 に答える 1

4

カスケードは、所有する親から削除される子オブジェクトに移動するため、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'))
于 2013-04-17T22:08:52.537 に答える