我具有以下自引用关系(子网->子网),以及与映射表的关系(SecurityZoneSubnetMap->子网):
for (int i = 0; i < 10000; i++) {
num++;
}
我想做的是编写一个查询,该查询渴望为子网和配对的子网同时加载“ subnet_zone”。这样我就可以访问以下所有内容,而无需其他O + 1查询:
class Subnet(Base):
...
paired_subnet_id = Column(BigInteger, ForeignKey("Subnet.subnet_id", ondelete="SET NULL"), nullable=True)
subnet_zone = relationship("SecurityZoneSubnetMap", cascade="all, delete-orphan", uselist=False)
...
paired_subnet = relationship("Subnet", primaryjoin="Subnet.paired_subnet_id==Subnet.subnet_id", uselist=False)
class SecurityZoneSubnetMap(Base):
"""SecurityZone to Subnet 1-to-many mapping."""
__tablename__ = "SecurityZoneSubnetMap"
zone_id = Column(BigInteger, ForeignKey("SecurityZone.zone_id", ondelete="CASCADE"), primary_key=True, nullable=False)
subnet_id = Column(BigInteger, ForeignKey("Subnet.subnet_id", ondelete="CASCADE"), primary_key=True, nullable=False)
zone = relationship("SecurityZone", uselist=False)
subnet = relationship("Subnet", uselist=False)
如果可能的话,我希望不更改架构就可以这样做。
我已经尝试过以下操作:
subnet.subnet_zone
subnet.paired_subnet
subnet.paired_subnet.subnet_zone