我一直在通過很多網站瀏覽以試圖瞭解發生了什麼,但我真的需要一些直接幫助。如果我錯過了文檔中顯而易見的內容,我很抱歉。SQLAlchemy與association_proxy問題的關係
這裏就是我想要做的(我已經切出一切,但基本代碼):
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: Dependency rule tried to blank-out primary key column 'user_to_group.user_login' on instance '<UserToGroup at 0x7f33f49bd190>'
我希望它只是刪除user_to_group
表中的行並相應地更新對象以反映更改。
我有它當關系表沒有映射到一個對象之前的工作,but I need it to be mapped to an object to use inheritance
謝謝!有時候我會覺得我在閱讀文檔時會溺水。我認爲沒有什麼可以做得更好,但這只是一個有很多細節的話題。 –