Python 包含关系属性的自引用关系 处境
我有自我引用的多对多关系(几乎与同一标题的sqlalchemy手动输入相同)。此关系由表Python 包含关系属性的自引用关系 处境,python,entity-framework,sqlalchemy,self-reference,Python,Entity Framework,Sqlalchemy,Self Reference,我有自我引用的多对多关系(几乎与同一标题的sqlalchemy手动输入相同)。此关系由表实体\u权重控制。这个代码有效 问题: 如何在类Entity中包含表示表列Entity\u weights.weight的属性。假设该属性将被称为Entity.child\u weights。重要的是Entity.child\u entities和Entity.child\u weights的排名相同 entity_weights = Table('entity_weights', Base.metadata
实体\u权重
控制。这个代码有效
问题:
如何在类Entity
中包含表示表列Entity\u weights.weight
的属性。假设该属性将被称为Entity.child\u weights
。重要的是Entity.child\u entities
和Entity.child\u 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'
)
我在这个场景中找到的最干净的解决方案是,通过在
实体
上添加实体权重
作为一对多关系来打破子实体
关系,并使用代理来代理权重
值以及多对多关系的远端:
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")