day12-sqlalchemy 外键关联

一、前言

  之前我们是针对一张表的,限制我们增加外键的限制,来试试,看看出现什么样的情况

二、外键关联

2.1、表关系图

2.2、外键关联

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,DATE,ForeignKey  #导入外键
from sqlalchemy.orm import  relationship  #创建关系

engine = create_engine("mysql+pymysql://root:111111@120.26.225.159:3306/qigaodb",
                       encoding="utf-8")

Base = declarative_base() #生成orm基类

class Student(Base):
    __tablename__ = "student"
    id = Column(Integer,primary_key=True)
    name = Column(String(32),nullable=False)
    register_day = Column(DATE,nullable=False)

    def __repr__(self):
        return "<{0} name:{1}>".format(self.id,self.name)


class StudyRecord(Base):
    __tablename__ = "study_record"
    id = Column(Integer,primary_key=True)
    day = Column(Integer,nullable=False)
    status = Column(String(32),nullable=False)
    stu_id = Column(Integer,ForeignKey("student.id"))   #关联外键
   #relationship表示,允许你在student表里通过backref字段反向查出所有它在study_record表里的关联项
    student = relationship("Student",backref="my_study_record")  

    def __repr__(self):
        return "<{0} name:{1} stu_id:{2}>".format(self.student.name,self.day,self.stu_id)

Base.metadata.create_all(engine) #创建表

注意:这个relationship表示,允许你在student表里通过backref字段反向查出所有它在study_record表里的关联项

三、relationship的作用

3.1、作用

  关联student表,然后我只需要在study_record里通过student这个字段,就可以去查Student类里面所有的字段,反过来利用backref="my_study_record"中的my_study_record,在student表里通过my_study_record这个字段反查study_record类里面的所有字段,然后代表着我的student在这里只需写上stu_obj.my_study_record就可以获取study_record的数据

from sqlalchemy.orm import  sessionmaker

Session_class = sessionmaker(bind=engine)
session = Session_class()

stu_obj = session.query(Student).filter_by(name="zhangqigao").first()
print(stu_obj.my_study_record)  #获取study_record的数据

#输出
[<zhangqigao name:1 stu_id:1>]

注意: relationship只是在内存里面存了这么一个关联,并没有在数据库里面存这个关系,使它变的更加简单。

3.2、原理图

 

posted @ 2017-10-20 10:06  帅丶高高  阅读(476)  评论(0编辑  收藏  举报