zoukankan      html  css  js  c++  java
  • 循序渐进Python3(十)-- 3 -- SqlAlchemy

    使用sqlalchemy 创建外键关联

    class Host(Base):
    __tablename__ = 'host'
    id = Column(Integer, primary_key=True, autoincrement=True)
    host_name = Column(String(64), nullable=False)
    ip_addr = Column(String(128), unique=True, nullable=False)
    port = Column(Integer, default=22)
    host_user = Column(String(64), nullable=False)
    host_pw = Column(String(64), nullable=False)


    class Work(Base):
    __tablename__ = 'work' # 实际创建的表名
    id = Column(Integer, primary_key=True, autoincrement=True)
    work_name = Column(String(64), unique=True, nullable=False)


    class HostWork(Base):
    __tablename__ = 'hostwork'
    id = Column(Integer, primary_key=True, autoincrement=True)
    host_id = Column(Integer, ForeignKey('host.id'))
    work_id = Column(Integer, ForeignKey('work.id'))

    host_info = relationship("Host", backref="hostinfo")
    work_info = relationship("Work", backref="workinfo")

    通过含有relationship的表去查找相关联的表 叫正向查找;
    反之,则叫反向查找;
    看个例子:
    # 利用relationship先反向查找 “操作类型和主机id” 在正向查找主机详细信息
    works = new_session.query(init_db.Work).filter(init_db.Work.work_name == work_type[0]).first()
    for item in works.workinfo:
    print(item.host_info.host_name)




  • 相关阅读:
    form 编译命令
    Form文件夹开发步骤
    使用View为Data Source的Form开发要点
    spring2.0包说明【转】
    Zero to One读后感
    Fourth glance in Go
    Third glance in Go
    Second glance in Go
    First glance in Go
    MongoDB 安装
  • 原文地址:https://www.cnblogs.com/wumingxiaoyao/p/5980788.html
Copyright © 2011-2022 走看看