繁体   English   中英

在SQLalchemy中访问相关记录数据

[英]Accessing related record data in SQLalchemy

我正在创建包含其名称和IP地址的以太网交换机数据库。 我还将活动端口的列表存储在该交换机中(目前处于UP状态的端口)。 对于交换机,我将其IP地址用作主键。 不幸的是问题始于端口列表。 它们可以具有重复的名称和编号(因为每个交换机可以具有端口号1,也可以具有名为“上行链路”的端口)。

所以我的想法是使用端口ID的形式,例如“ switch_ip:port_name”:“ 1.2.3.4:Gi0/1”或“ 4.5.6.7:20”,以防端口号只是数字而不是名称。

我想这样做,以便Session.merge()起作用。 所以这是我的看法:

class Switch(Base):
    __tablename__ = 'switches'

    name = Column(String(128), nullable=False)
    ip = Column(String(15), primary_key=True, nullable=False)

    ports = relationship("Port", order_by="Port.id", backref="switch")

    def __repr__(self):
            return "<Switch(name='%s', ip='%s')>" % (self.name, self.ip)

class Port(Base):
    __tablename__ = 'ports'

    id = Column(String(160), primary_key=True)
    number = Column(Integer) 
    name = Column(String(32)) 
    description = Column(String(255))

    switch_ip = Column(String(15), ForeignKey('switches.ip'))
    macs = relationship("Mac", order_by="Mac.mac", backref="port")

    def __init__(self, id, name, description, number = None):
            self.name = name
            self.description = description
            self.number = number
            self.id = self.switch_ip + ":" + name

    def __repr__(self):
            return "<Port(switch='%s', name='%s', description='%s')>" % (self.switch_ip, self.name, self.description)

并感谢我可以做这样的事情:

sw = Switch(name='some-switch',ip='1.2.3.4')
sw.ports = [ Port(name='Gi0/666', description='Uplink'), Port(name='Gi0/24', description='Apartament2') ]

不幸的是,在Port.__init__它的属性switch_ip为空( None )。 但是,在通过Session.add()Session.merge()将其存储在数据库中之后,它得到的值已正确填充为1.2.3.4。 但是为时已晚。 那么如何在Port.__init__获取switch_ip值呢?

这是一个使用上下文相关列插入默认值的解决方案(在此处记录-http: //docs.sqlalchemy.org/en/latest/core/defaults.html )。 首先,我们创建返回由IP和端口名称组成的专有名称的函数:

def portid(context):
    return context.current_parameters['switch_ip'] + ':' + context.current_parameters['name']

然后更新对象定义:

class Port(Base):
    __tablename__ = 'ports'

    id = Column(String(160), primary_key=True, default=portid)
    number = Column(Integer) 
    name = Column(String(32)) 
    description = Column(String(255))

    switch_ip = Column(String(15), ForeignKey('switches.ip'))
    macs = relationship("Mac", order_by="Mac.mac", backref="port")

    def __repr__(self):
            return "<Port(switch='%s', name='%s', description='%s')>" % (self.switch_ip, self.name, self.description)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM