【问题标题】:SQLAlchemy self-referential many to many with extra association data带有额外关联数据的 SQLAlchemy 自引用多对多
【发布时间】: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_customeris_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


【解决方案1】:

它认为您应该能够使用 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' 可能适用于此目的。

【讨论】:

  • 我可能解释的不是很好。我已经可以通过定位OrganisationOrganisationMap插入更新 ok。我希望能够根据is_customeris_supplier 字段select 相关对象。例如organisation_1.associated 将返回相关组织的列表。我需要为organisation_1.suppliersorganisation_1.customers 做同样的事情
猜你喜欢
  • 2014-09-30
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2011-12-05
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
相关资源
最近更新 更多