我一直在浏览许多网站以试图了解发生了什么,但我真的需要一些直接的帮助。如果我错过了文档中明显的内容,我很抱歉。
这是我正在尝试做的事情(除了基本代码,我已经删除了所有内容):
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
表中的行并相应地更新对象以反映更改。
当关系表没有映射到对象时,我已经让它工作了,但是我需要将它映射到对象以使用继承