【发布时间】:2016-08-01 04:47:23
【问题描述】:
我有以下带有多对多自我引用的基本 SQLAlchemy 模型:
class Organisation(Base):
__tablename__ = 'organisation'
name = Column(String(50))
url = Column(String(128))
associated = relationship(
'Organisation',
secondary="organisation_map",
primaryjoin="Organisation.id==organisation_map.c.organisation_id",
secondaryjoin="Organisation.id==organisation_map.c.assoc_organisation_id",
backref="account_organisation"
)
关联表如下所示:
class OrganisationMap(Base):
__tablename__ = 'organisation_map'
organisation_id = Column(Integer, ForeignKey('organisation.id'))
assoc_organisation_id = Column(Integer, ForeignKey('organisation.id'))
is_customer = Column(Boolean, default=False)
is_supplier = Column(Boolean, default=False)
关联表包含额外的数据,is_customer 和 is_supplier,我希望能够从模型本身引用它们,例如:
class Organisation(Base):
...
def get_suppliers(self):
pass
def get_customers(self):
pass
目前,如果不先查询关联表OrganisationMap,获取“客户”或“供应商”的ids,然后查询@,我无法获得这样的列表987654328@ 带有 ids 列表的表。
这可能吗?
【问题讨论】:
-
见this question。自引用部分应该只需要对配置进行名义上的更改。
标签: python sqlalchemy many-to-many self-reference