• 技术文章 >后端开发 >Python教程

    Python下SQLAlchemy关系操作的介绍(附代码)

    不言不言2018-10-23 16:50:13转载822
    本篇文章给大家带来的内容是关于Python下SQLAlchemy关系操作的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

    关系数据库是建立在关系模型基础上的数据库,所以表之间的关系在数据库编程中尤为重要。本节围绕在SQLAlchemy中如何定义关系及如何使用关系进行查询进行讲解,使读者能够快速掌握SQLAlchemy的关系操作。

    1、案例

    设计3个实体表:班级表class、学生表student、老师表teacher和1个关系表:class_teacher。班级与学生为一对多关系,班级与老师之间为多对多关系。

    from sqlalchemy import Table,Column,Integer,ForeignKey,String
    from sqlalchemy.orm import relationship,backref
    from sqlalchemy.ext.declarative import declarative_base
    
    Base=declarative_base()
    
    class Class(Base):
        __tablename__='class'
        class_id=Column(Integer,primary_key=True)
        name=Column(String(50))
        level=Column(Integer)
        address=Column(String(50))
    
        class_teachers=relationship("ClassTeacher",backref="class")
        students=relationship("Student",backref="class")
    
    class Student(Base):
        __tablename__='student'
        student_id=Column(Integer,primary_key=True)
        name=Column(String(50))
        age=Column(Integer)
        gender=Column(String(10))
        address=Column(String(50))
        class_id=Column(Integer,ForeignKey('class.id'))
    
    class Teacher(Base):
        __tablename__='teacher'
        teacher_id=Column(Integer,primary_key=True)
        name=Column(String(50))
        gender=Column(String(10))
        telephone=Column(String(50))
        address=Column(String(50))
        class_teachers=relationship("ClassTeacher",backref="teacher")
    
    class ClassTeacher(Base):
        __tablename__='class_teacher'
        teacher_id=Column(Integer,ForeignKey('teacher.teacher_id'),primary_key=True)
        class_id=Column(Integer,ForeignKey("class.id"),primary_key=True)

    代码中用了4个SQLAlchemy模型对4个表进行了定义,其中与关系定义相关的部分如下:

    class_id=Column(Integer,ForeignKey('class.id'))
    students=relationship("Student",backref="calss")

    其中的backref参数为可选参数,如果设置backref,则此语句同时设置了 从父表对子表的引用。

    class=session.query(Class).filter(Clss.name=="三年二班").first()
    
    for student in class_.students:
        print(student)
    class=session.query(Class).filter(Class.name=="三年二班").first()
    for class_teacher in class_.class_teachers:
        teacher=class_teacher.teacher
        print(teacher)
    上述代码中class_teacher.teacher是在模型teacher中针对ClassTeacher定义的反向引用。

    2、连接查询

    在实际开发中,有了关系就必不可少地会有多表连接查询的需求。下面通过实际例子演示如果进行多表连接查询。

    在查询语句中可以使用join关键字进行连接查询,打印出所有三年级学生的姓名:

    students=session.query(Student).join(Class).filter(Class.level==3).all()
    for student in students:
        print(student.namr)

    上述查询函数会自动把外键关系作为连接条件,该查询被SQLAlchemy自动翻译为如下SQL语句并执行:

    SELECT student.student_id AS student_student_id,
        student.name AS student.name,
        student.age AS student.age,
        student.gender AS student.gender,
        student.address AS student.address,
        student.class_id AS student_class_id
    FROM student JOIN class ON student.class_id=class.class_id
    WHERE class.leve=?
    (3,)

    如果需要将被连接表的内心同样打印出来,则可以在query中指定多个表对象。

    下面的语句在打印出所有三年级学生姓名的同时,打印出其所在班级的名字。

    for student,class_ in session.query(Student,Class).join(Class).filter(Class.level==3).all():
        print(student.name,class_.name)

    上述查询函数会自动把外键关系作为连接条件,该查询被SQLAlchemy自动翻译为如下SQL语句并执行:

    SELECT student.student_id AS student_student_id,
        student.name AS student.name,
        student.age AS student.age,
        student.gender AS student.gender,
        student.address AS student.address,
        student.class_id AS student_class_id,
        class.class_id AS class_class_id,
        class.name AS class_name,
        class.level AS class_level,
        class.address AS class_location
    FROM student JOIN class ON student.class_id=class.class_id
    WHERE class.leve=?
    (3,)

    如果需要用除外键外的其他字段作为连接条件,则需要开发者在join中自行设置。下面打印出所有班级的address与学生的address相同的学生的姓名:

    for student_name, in session.query(Student.name).join(Class,Class.address==Student.address).filter(Class.level==3).all():
        print(student_name)

    上述查询函数根据开发者指定的语句作为连接条件,并且因为直接指定了被查询的字段,所以减少了实际SQL中的被查询字段,提高了性能。该查询被SQLAlchemy自动翻译为如下SQL语句执行:

    SELECT student.name AS student_name, FROM student JOIN class ON student.address=class.address

    以上就是Python下SQLAlchemy关系操作的介绍(附代码)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault思否,如有侵犯,请联系admin@php.cn删除
    专题推荐:python
    上一篇:Python编程下SQLAlchemy查询条件设置的方法介绍 下一篇:Python中matplotlib库的用法介绍
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• js中sqlalchemy的实例详解• python第六十六天--sqlalchemy• 详解Python利用flask sqlalchemy实现分页• Python下SQLAlchemy的简单介绍• Python编程下SQLAlchemy查询条件设置的方法介绍
    1/1

    PHP中文网