循序渐进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)




原文地址:https://www.cnblogs.com/wumingxiaoyao/p/5980788.html