我有sqlalchemy模型:
class Equipment(Base):
__tablename__ = 'equipment'
id = Column(Integer, primary_key=True)
ports = db.relationship('SnmpPort', passive_deletes=True, backref='Equipment')
class SnmpPort(Base):
__tablename__ = 'snmp_ports'
id = Column(Integer, primary_key=True)
equipment = Column('equipment', Integer, ForeignKey('equipment.id'))
@property
def Link(self):
if self.Link1 is not None:
return self.Link1
if self.Link2 is not None:
return self.Link2
return None
@property
def ToSnmpPort(self):
if self.Link:
if self.Link.portid1 == self.id:
return self.Link.SnmpPort2
else:
return self.Link.SnmpPort1
return None
class Link(Base):
__tablename__ = 'link'
id = Column(Integer, primary_key=True)
portid1 = Column(Integer, ForeignKey('snmp_ports.id'))
SnmpPort1 = relation('SnmpPort', foreign_keys=portid1,
backref=backref("Link1", uselist=False))
portid2 = Column(Integer, ForeignKey('snmp_ports.id'))
SnmpPort2 = relation('SnmpPort', foreign_keys=portid2,
backref=backref("Link2", uselist=False))
active = Column(Boolean, default=True)
现在我必须写这样的查询:
equipment = Equipment.query\
.options(joinedload_all(Equipment.ports, SnmpPort.Link1, Link.SnmpPort1))\
.options(joinedload_all(Equipment.ports, SnmpPort.Link2, Link.SnmpPort1))\
.options(joinedload_all(Equipment.ports, SnmpPort.Link2, Link.SnmpPort2))\
.options(joinedload_all(Equipment.ports, SnmpPort.Link2, Link.SnmpPort1))\
.get(3097)
for port in equipment.ports:
print port.ToSnmpPort
当我想添加更多联接时,我必须添加四次,我可以避免吗? 我可以使用hybrid_property来编写这样的查询:
equipment = Equipment.query\
.options(joinedload_all(Equipment.ports, SnmpPort.Link, Link.SnmpPort1))\
.options(joinedload_all(Equipment.ports, SnmpPort.Link, Link.SnmpPort2))\
.get(3097)
是否可以使用短查询,如果使用Link.SnmpPort1 / 2做一些技巧,可以更短吗?