Skip to main content
 首页 » 编程设计

python之自引用关系,包括关系属性

2025年05月04日13me-sa

情况

我有自引用多对多关系(几乎与相同标题的 sqlalchemy 手册条目相同)。此关系由表 entity_weights 管理。此代码有效!

问题

我如何在类 Entity 中包含一个属性来表示表列 entity_weights.weight。假设该属性将被称为 Entity.child_weights。 Entity.child_entities 和 Entity.child_weights 的等级相同很重要。

entity_weights = Table('entity_weights', Base.metadata, 
    Column('id',Integer, primary_key=True), 
    Column('parent_entity_id',Integer, ForeignKey('entity.id')), 
    Column('entity_id',Integer, ForeignKey('entity.id')), 
    Column('weight',Float)) 
 
 
class Entity(Base): 
    __tablename__ = 'entity' 
 
    id = Column(Integer, primary_key=True) 
    name = Column(String) 
    domicile_id = Column(Integer, ForeignKey('domicile.id')) 
    entity_type = Column('type',Enum('asset','institution','model')) 
    source_table_id = Column(Integer) 
    child_entities = relationship('Entity', 
                        secondary=entity_weights, 
                        primaryjoin=id==entity_weights.c.parent_entity_id, 
                        secondaryjoin=id==entity_weights.c.entity_id, 
                        backref='parent_entity_id' 
                        ) 

请您参考如下方法:

我为这种情况找到的最干净的解决方案是通过添加 entity_weights 作为 Entity 上的一对多关系来打破 child_entities 关系 并使用 association proxy代理 weight 值以及多对多关系的远程端:

class EntityWeight(Base): 
    __tablename__ = "entity_weights" 
    id = Column(Integer, primary_key=True) 
    parent_entity_id = Column(Integer, ForeignKey('entity.id')) 
    entity_id = Column(Integer, ForeignKey('entity.id')) 
    weight = Column(Float) 
    entity = relationship("Entity", primaryjoin=lambda: EntityWeight.entity_id == Entity.id) 
 
class Entity(Base): 
    ... 
    _child_weights = relationship(EntityWeight, primaryjoin=id == EntityWeight.parent_entity_id) 
    child_weights = association_proxy("_child_weights", "weight") 
    child_entities = association_proxy("_child_weights", "entity")