pythonのsqlalchemy外键关联查询
1 #!/usr/bin/env python 2 3 import sqlalchemy 4 from sqlalchemy import create_engine 5 from sqlalchemy.ext.declarative import declarative_base 6 from sqlalchemy import Column,Integer,String,DATE,Enum,ForeignKey 7 from sqlalchemy.orm import sessionmaker,relationship 8 9 # 创建连接 echo=True 就会打印出所有过程信息 10 engine = create_engine("mysql+pymysql://root:root@localhost/testuser",encoding="utf-8",echo=True) 11 12 # 13 Base = declarative_base() # 生成orm基类 14 15 class Student(Base): 16 __tablename__ = "student" 17 id = Column(Integer,primary_key=True) 18 name = Column(String(32),nullable=False) 19 register_Date = Column(DATE,nullable=False) 20 21 def __repr__(self): 22 return "<%s name:%s>"% (self.id,self.name) 23 24 class StudyRecord(Base): 25 __tablename__ = "study_record" 26 id = Column(Integer, primary_key=True) 27 day = Column(Integer,nullable=False) 28 status = Column(String(32),nullable=False) 29 stu_id = Column(Integer,ForeignKey("student.id")) 30 31 # 关系 32 student = relationship("Student",backref="my_study_record") 33 def __repr__(self): 34 return "< day:%s status:%s>" % (self.id, self.status) 35 36 37 Base.metadata.create_all(engine) # 创建表结构 38 39 Session_class = sessionmaker(bind=engine) # 创建与数据库的会话session class 注意,这里返回的是一个class,不是实例 40 41 session = Session_class() 42 43 # s1 = Student(name="Tom",register_Date="2018-08-08") 44 # s2 = Student(name="Jerry",register_Date="2018-06-08") 45 # s3 = Student(name="Lucy",register_Date="2018-08-28") 46 # s4 = Student(name="Lily",register_Date="2018-08-18") 47 # 48 # study_obj1 = StudyRecord(day=1,status="Yes",stu_id=1) 49 # study_obj2 = StudyRecord(day=2,status="No",stu_id=1) 50 # study_obj3 = StudyRecord(day=3,status="Yes",stu_id=1) 51 # study_obj4 = StudyRecord(day=1,status="Yes",stu_id=2) 52 53 # session.add_all([s1,s2,s3,s4,study_obj1,study_obj2,study_obj3,study_obj4]) 54 # session.commit() 55 56 stu_obj = session.query(Student).filter(Student.name=="Tom").first() 57 58 print(stu_obj.my_study_record)
解释:
(1)创建表:将43-54行代码解封,此时会自动为您创建相关联的表
重点理解:
32行:student = relationship("Student",backref="my_study_record")
这里需要引入 from sqlalchemy.orm import sessionmaker,relationship
32行代码用途,可以通过Student 在表StudyRecord中直接引用表Student 那么可以通过 my_study_record 直接引用StudyRecord中的数据。这是因为他们两者存在外键关联,所以当我们执行第58行的时候,他就会根据外键去查询study_record 中的数据。
用心做人,用脑做事!----鹏鹏张