1.多对多的关系需要通过一张中间表来绑定他们之间的关系。
2. 先把两个需要做多对多的模型定义出来
3. 使用Table定义一个中间表,中间表一般就是包含两个模型的外键字段就可以了,并且让他们两个来作为一个“复合主键”。
4. 在两个需要做多对多的模型中随便选择一个模型,定义一个relationship属性,来绑定三者之间的关系,在使用relationship的时候,需要传入一个secondary=中间表对象名
数据库的配置变量、创建数据库引擎、创建模型类基类、创建session对象
from sqlalchemy import create_engine, Column, Integer, ForeignKey, String, TEXT, Boolean, DATE, DECIMAL
from sqlalchemy import Table
from sqlalchemy.ext.declarative import declarative_base
from datetime import date
from sqlalchemy.orm import sessionmaker,relationship,backref
# 数据库的配置变量
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'root'
PASSWORD = 'root'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
#创建数据库引擎
engine=create_engine(DB_URI)
#创建模型类基类
Base=declarative_base(engine)
#创建session对象
session=sessionmaker(engine)()
第一步:定义中间表
第三步:定义中间表的两个外键作为联合字段
temp_table=Table(
't_temp_tab1',
Base.metadata,
#第三步:定义中间表的两个外键作为联合字段
Column("s_id",Integer,ForeignKey('t_student1.id'),primary_key=True),
Column("c_id",Integer,ForeignKey('t_course1.id'),primary_key=True)
)
第二步:定义多对多的两个模型对象
学生表
class Student(Base):
__tablename__='t_student1'
id=Column(Integer,primary_key=True,autoincrement=True)
name=Column(String(30))
age=Column(Integer)
#第四步:定义关联关系,secondary=中间表的变量名
course_list=relationship('Course',backref='student_list',secondary=temp_table)
def __str__(self):
return f'{self.name}'
第四步:定义关联关系,secondary=中间表的变量名
特别注意1:course_list=relationship(‘Course’,backref=‘student_list’,secondary=temp_table)的写法;secondary=中间表的变量名
课程表
class Course(Base):
__tablename__='t_course1'
id = Column(Integer, primary_key=True, autoincrement=True)
c_name = Column(String(30))
def __str__(self):
return f'{self.c_name}'
插入数据
def save():
s1=Student(name='kobe',age=25)
s2=Student(name='zilv',age=18)
s3=Student(name='yyds',age=20)
c1=Course(c_name='python')
c2=Course(c_name='英语')
c3=Course(c_name='语文')
s1.course_list.append(c1)
s1.course_list.append(c2)
s1.course_list.append(c3)
s2.course_list.append(c1)
s2.course_list.append(c2)
s2.course_list.append(c3)
s3.course_list.append(c1)
s3.course_list.append(c2)
s3.course_list.append(c3)
session.add(s1)
session.add(s2)
session.add(s3)
session.commit()
查询数据
def query():
#查询kobe学生选了那些课
stu1=session.query(Student).filter(Student.name=='kobe').first()
print(stu1) #查询kobe学生
print(stu1.course_list) #查询kobe学生学了那些课
#查询python课程都别那些学生选了
cou1=session.query(Course).filter(Course.c_name=='python').first()
print(cou1) #查询python课程
print(cou1.student_list) #查询python课程被那些同学选择了
kobe
[<__main__.Course object at 0x00000244E4F03820>, <__main__.Course object at 0x00000244E4F03790>, <__main__.Course object at 0x00000244E4F038E0>]
python
[<__main__.Student object at 0x00000244E46DC430>, <__main__.Student object at 0x00000244E4F11BE0>, <__main__.Student object at 0x00000244E4F11B50>]
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/74169.html