![](/img/trans.png)
[英]Many-to-many, self-referential, non-symmetrical relationship (twitter model) via Association Object in SqlAlchemy
[英]SQLAlchemy self-referential many to many with extra association data
我有下面的基本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
,获取'customers'或'suppliers'的ID ,然后再查询具有ID列表的Organisation
表,就无法获得这样的列表。
这可能吗?
它认为您应该能够使用ORM事件来相应地插入和更新is_customer和is_supplier。 即:
@event.listens_for(OrganisationMap, 'after_insert')
@event.listens_for(OrganisationMap, 'after_update')
def update_organization_map(mapper, connection, target):
# query your db to fill this 2 fields accordingly
# you have the connection object
target.is_customer = query_to_fill_is_customer
target.is_supplier = query_to_fill_is_supplier
我不知道上面示例中使用的事件是否适合您。 请阅读SqlAlchemy ORM事件页面以获取完整列表:
http://docs.sqlalchemy.org/en/latest/orm/events.html
对于此目的,事件' before_insert '和before_update '可能很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.