繁体   English   中英

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_customeris_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM