Python 之 sqlalchemy 外鍵正反向關聯查詢
阿新 • • 發佈:2019-03-13
ado rst .com ges alt ive user 初始 反向查詢 表內容:
代碼:
#Author Kang import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship #創建對象的基類: Base = declarative_base() #定義User對象: class User(Base): #表的名字: __tablename__ = ‘user‘ #表的結構: userid = Column(Integer,primary_key=True) username = Column(String(20)) age = Column(Integer) department = Column(String(20)) salary = relationship("Salary",backref="test") #def __repr__(self): # return "userid:%s name:%s age:%s department:%s money:%s "%(self.userid,self.username,self.age,self.department,self.salary[0]) #定義Salary對象: class Salary(Base): #表的名字: __tablename__ = ‘salary‘ #表的結構: id = Column(Integer,primary_key=True) userid = Column(Integer,ForeignKey("user.userid")) month = Column(Integer) money = Column(Integer) def __repr__(self): return "%s" % (self.money) #初始化數據庫連接 engine = create_engine("mysql+pymysql://kang:[email protected]/test",encoding="utf-8") #創建session類型 DBSession = sessionmaker(bind=engine) #創建session對象 session = DBSession() print("Salary表,通過backref反向查詢User的姓名信息>>>>>>>>>>>>>>") e1 = session.query(Salary).filter_by(userid=3).first() print(e1.test.username,e1.money) print("user表,正向查詢salary工資信息>>>>>>>>>>>>>>>>>>>>>>>>") res = session.query(User).filter_by(username=‘MingKang‘).first() print(res.username,res.salary[0])
結果:
Salary表,通過backref反向查詢User的姓名信息>>>>>>>>>>>>>>
MingKang 12000
user表,正向查詢salary工資信息>>>>>>>>>>>>>>>>>>>>>>>>
MingKang 12000
Python 之 sqlalchemy 外鍵正反向關聯查詢