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、原理图

 

转载于:https://www.cnblogs.com/zhangqigao/articles/7698053.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值