1. 程式人生 > >sqlalchemy操作----外鍵關聯,relationship

sqlalchemy操作----外鍵關聯,relationship

huang integer -- password sql 通過 ext kref day

...

#!_*_coding:utf-8_*_
#__author__:"Alex huang"
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 relationship


engine = create_engine("mysql+pymysql://hrg:[email protected]:3306/test",encoding=‘utf8‘)
Base = declarative_base()  #生成orm基類

class students(Base):
    __tablename__ = ‘students‘ #表名
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    password = Column(String(64))
    def __repr__(self):
        return "id:%s name:%s" %(self.id,self.name)

class studyrecord(Base):
    __tablename__ = ‘studyrecord‘ #表名
    id = Column(Integer, primary_key=True)
    day = Column(String(32))
    status = Column(String(32))
    stu_id = Column(Integer,ForeignKey("students.id"))  #創建外鍵
    students = relationship("students",backref="my_studyrecord")  #創建關系,是在內存中映射的,沒有實際創建表,
    #backref回調引用,students表可以通過my_studyrecord來引用studyrecord的數據
    def __repr__(self):
        return "%s day:%s status:%s" %(self.students.name,self.day,self.status)

Base.metadata.create_all(engine)  #創建表
Session_class = sqlalchemy.orm.session.sessionmaker(bind=engine)  # 創建與數據庫的會話session class ,註意,這裏返回給session的是個class,不是實例
Session = Session_class()  # 生成session實例
#
#插入  第一次運行先插入數據
# s1 = students(name=‘hrg‘,password=‘111‘)
# s2 = students(name=‘keke‘,password=‘122‘)
# s3 = students(name=‘tom‘,password=‘333‘)
# r1 = studyrecord(day=‘1‘,status=‘yes‘,stu_id=‘1‘)
# r2 = studyrecord(day=‘1‘,status=‘yes‘,stu_id=‘2‘)
# r3= studyrecord(day=‘2‘,status=‘no‘,stu_id=‘1‘)
# r4 = studyrecord(day=‘3‘,status=‘yes‘,stu_id=‘1‘)
# r5 = studyrecord(day=‘3‘,status=‘yes‘,stu_id=‘2‘)
#
# Session.add_all([s1,s2,s3,r1,r2,r3,r4,r5])
# Session.commit()

data = Session.query(students).filter(students.name==‘hrg‘).first()  #先students表裏名稱為hrg的第一條記錄
print(data.my_studyrecord) #打印hrg在studyrecord中的相關記錄

  ...

sqlalchemy操作----外鍵關聯,relationship