zhoujun.g 发表于 2018-8-16 09:32:55

Python 学习笔记 - SQLAlchemy(下)

  
from sqlalchemy import create_engine
  
from sqlalchemy.ext.declarative import declarative_base
  
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index,Table
  
from sqlalchemy.orm import sessionmaker, relationship
  
engine = create_engine("mysql+pymysql://yli:yli@sydnagios:3306/mydb", max_overflow=5)
  
Base = declarative_base()
  

  
class HostToHostUser(Base):
  
    __tablename__ = 'host_to_host_user'
  
    nid = Column(Integer, primary_key=True,autoincrement=True)
  
    host_id = Column(Integer ,ForeignKey('host.nid'))
  
    host_user_id = Column(Integer, ForeignKey('host_user.nid'))
  

  
    #配置关系
  
    host = relationship("Host", backref='h')
  
    host_user = relationship("HostUser", backref='u')
  

  
class Host(Base): # metaclass,Host.table对象
  
    __tablename__ = 'host'
  
    nid = Column(Integer, primary_key=True,autoincrement=True)
  
    hostname = Column(String(32))
  
    port = Column(String(32))
  
    ip = Column(String(32))
  

  
class HostUser(Base):
  
    __tablename__ = 'host_user'
  
    nid = Column(Integer, primary_key=True,autoincrement=True)
  
    username = Column(String(32))
  

  
#def init_db():
  
#    Base.metadata.create_all(engine)
  
#
  
# def drop_db():
  
#   Base.metadata.drop_all(engine)
  
#init_db()
  

  
Session = sessionmaker(bind=engine)
  
session = Session()
  

  
host_obj = session.query(Host).filter(Host.hostname=='c1').first()
  
print(host_obj.nid)
  
print(host_obj.hostname)
  
# 第三表对应的对象(逆向查询)
  
print(host_obj.h)
  
# 循环获取的第三表对应的对象
  
for item in host_obj.h:
  
    print(item.host_user,item.host_user.nid,item.host_user.username)
  
    --------------
  
"C:\Program Files\Python3\python.exe" "C:/Users/yli/Documents/Tencent Files/38144205/FileRecv/s13课上代码/s13课上代码/s13day13课上代码/s13day13_课上代码/ORM—de,p.py"
  
1
  
c1
  
[, , ]
  
1 root
  
2 db
  
3 nb
  

  
Process finished with exit code 0


页: [1]
查看完整版本: Python 学习笔记 - SQLAlchemy(下)