我有三个表:设备、插槽、端口。
- 设备将有多个插槽
- 插槽将有多个端口,但属于单个设备
- 端口属于单个 Slot
根据我的经验,这显示为:
- 设备(一对多)插槽
- 插槽(一对多)端口
我正在尝试在我的 Devices 类中建立一个关系,该关系将为我提供所有关联的 Ports 对象(无论插槽如何)。我想不通。关联表看起来很接近,但我无法从周围的例子中辨别出如何做我想做的事。
class Devices(Base):
__tablename__ = 'devices'
__table_args__ = {
'mysql_engine' : 'MyISAM',
'mysql_charset': 'latin1'
}
did = Column( INTEGER, primary_key=True )
hostname = Column( VARCHAR(255) )
site = Column( INTEGER, ForeignKey('site.sid'), default=0 )
model = Column( INTEGER )
fqdn = Column( VARCHAR(255) )
slots = relationship("Slots")
changes = relationship("PortStateLog")
ports = relationship("Ports", primaryjoin="and_(Slots.device==Devices.did,Ports.slot==Slots.sid)")
class Slots(Base):
__tablename__ = 'slots'
__table_args__ = {
'mysql_engine' : 'MyISAM',
'mysql_charset': 'latin1'
}
sid = Column( INTEGER, primary_key=True )
device = Column( INTEGER, ForeignKey('devices.did'), default=None )
slot = Column( VARCHAR(10) )
module = Column( INTEGER )
slot_status = Column( INTEGER )
card_status = Column( INTEGER )
ports = relationship("Ports", primaryjoin="Ports.slot==Slots.sid")
class Ports(Base):
__tablename__ = 'ports'
__table_args__ = {
'mysql_engine' : 'MyISAM',
'mysql_charset': 'latin1'
}
pid = Column( INTEGER, primary_key=True )
slot = Column( INTEGER, ForeignKey('slots.sid'), default=None )
port = Column( INTEGER )
name = Column( VARCHAR(200) )
status = Column( INTEGER )
description = Column( VARCHAR(200) )
op_status = Column( VARCHAR(40) )
substatus = Column( INTEGER(4) )
type = Column( INTEGER )
clean = Column( TINYINT(4) )
speed = Column( INTEGER(10) )
duplex = Column( CHAR(1) )
sfp = Column( INTEGER )
以上是我到目前为止所拥有的。我只是希望下面的最后一行返回所有端口:
d = session.query(Devices).first()
d.ports
非常感谢任何帮助。