我有两个班级作为多对多关系A和B,缩短为显示基本关系:
class A(Base):
bclss = relationship("B",
backref = "aclss",
secondary = "a_b_association",
collection_class = attribute_mapped_collection('identifier'))
a_b_association_table = Table('a_b_association', Base.metadata,
Column('a_id', Integer, ForeignKey('a.id')),
Column('b_id', Integer, ForeignKey('b.id')) )
因此,A的实例可以添加B的实例,并在由标识符键入的字典中引用...但是B实例只包含其对象的[list],并且我想要一个镜像接口,以便拉出通过字典中的标识符键与b实例相关的实例。镜像b上的关系语句并引用相同的关联表是行不通的,所以我想到了一个我还不知道如何在sqlalchemy中实现的区域。
所以,即使这不是100%明确,我的问题是:
如何获取字典,属性映射集合在两个相关的多个关系项中,每个方可以通过字典键来拉取相关项而不是我得到的:一个不对称的单边字典/其他边列表界面。
答案 0 :(得分:1)
我相信这正是您所寻找的(您只需要在与多个backref
的多对多关系中定义attribute_mapped_collection
关系:
from sqlalchemy import Column, ForeignKey, Integer, String, Table, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship, sessionmaker
from sqlalchemy.orm.collections import attribute_mapped_collection
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
a_b_association_table = Table(
'a_b_association', Base.metadata,
Column('a_id', Integer, ForeignKey('a.id')),
Column('b_id', Integer, ForeignKey('b.id'))
)
class B(Base):
__tablename__ = 'b'
id = Column(String, primary_key=True)
a_instances = relationship(
A,
backref = backref(
'b_instances',
collection_class = attribute_mapped_collection('id'),
),
secondary = a_b_association_table,
collection_class = attribute_mapped_collection('id'),
)
engine = create_engine('sqlite://')
Base.metadata.bind = engine
Base.metadata.create_all()
Session = sessionmaker(bind=engine)
session = Session()
a1, a2, a3 = A(id=1), A(id=2), A(id=3)
b1, b2, b3 = B(id='a'), B(id='b'), B(id='c')
session.add_all([a1, a2, a3, b1, b2, b3])
session.flush()
print(a1.b_instances)
print(b1.a_instances)
a1.b_instances[b1.id] = b1
a1.b_instances[b2.id] = b2
b1.a_instances[a1.id] = a1
b1.a_instances[a2.id] = a2
session.flush()
session.expunge_all()
a1 = session.query(A).get(1)
b1 = session.query(B).get('a')
print(a1.b_instances)
print(b1.a_instances)
输出:
{}
{}
{u'a': <__main__.B object at 0x2816490>, u'b': <__main__.B object at 0x28b0350>}
{1: <__main__.A object at 0x28ac9d0>, 2: <__main__.A object at 0x28b0650>}