我使用双向association_proxy
来关联属性Group.members
和User.groups
。我在从Group.members
删除成员时遇到问题。特别是,Group.members.remove
会成功删除Group.members
,中的条目,但会留下None
代替User.groups
中的相应条目。< / p>
更具体地说,以下(minimal-ish)代表性代码段未能通过其最后一个断言:
import sqlalchemy as sa
from sqlalchemy.orm import Session
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Group(Base):
__tablename__ = 'group'
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
name = sa.Column(sa.UnicodeText())
members = association_proxy('group_memberships', 'user',
creator=lambda user: GroupMembership(user=user))
class User(Base):
__tablename__ = 'user'
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
username = sa.Column(sa.UnicodeText())
groups = association_proxy('group_memberships', 'group',
creator=lambda group: GroupMembership(group=group))
class GroupMembership(Base):
__tablename__ = 'user_group'
user_id = sa.Column(sa.Integer, sa.ForeignKey('user.id'), primary_key=True)
group_id = sa.Column(sa.Integer, sa.ForeignKey('group.id'), primary_key=True)
user = sa.orm.relationship(
'User',
backref=sa.orm.backref('group_memberships', cascade="all, delete-orphan"))
group = sa.orm.relationship(
'Group',
backref=sa.orm.backref('group_memberships', cascade="all, delete-orphan"),
order_by='Group.name')
if __name__ == '__main__':
engine = sa.create_engine('sqlite://')
Base.metadata.create_all(engine)
session = Session(engine)
group = Group(name='group name')
user = User(username='user name')
group.members.append(user)
session.add(group)
session.add(user)
session.flush()
assert group.members == [user]
assert user.groups == [group]
group.members.remove(user)
session.flush()
assert group.members == []
assert user.groups == [] # This assertion fails, user.groups is [None]
我尝试按照SQLAlchemy relationship with association_proxy problems和How can SQLAlchemy association_proxy be used bi-directionally?的答案,但似乎没有帮助。
答案 0 :(得分:2)
我几乎完全是偶然发现了your problem,因为我试图找出正在发生的事情。
由于数据库中没有任何数据,我添加了session.commit()
。事实证明(来自链接的答案):
在数据库收到当前事务的COMMIT(这就是session.commit()所做的事情)之前,更改不会永久保留到磁盘或对其他事务可见。
因为您只是.flush()
更改,sqlalchemy永远不会重新查询数据库。您可以通过添加:
import logging
logging.getLogger('sqlalchemy').setLevel(logging.INFO)
logging.getLogger('sqlalchemy').addHandler(logging.StreamHandler())
然后只需运行您的代码。它将显示所有在运行时运行的查询。然后,您可以将session.flush()
更改为session.commit()
然后重新运行,并且您会看到在SELECT
之后运行多个commit
语句。
看起来session.expire(user)
或session.refresh(user)
也会强制刷新用户。我不确定是否有办法强制更新传播到另一个对象而不明确它(或者甚至是否可取)。