flask-sqlalchemy 多对多操作示例

3个月前 129次点击 来自 Flask

Step1 生成app与db实例

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///d:\\tmp\\test.db'
db = SQLAlchemy(app)

Step2 定义模型

tags = db.Table('tags', db.Column('student_id', db.Integer, db.ForeignKey('student.id')),
                db.Column('course_id', db.Integer, db.ForeignKey('course.id')))


class Student(db.Model):
    __tablename__ = 'student'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    course = db.relationship('Course', secondary=tags)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "Student's name :{}".format(self.name)


class Course(db.Model):
    ___tablename__ = 'course'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "Course's name :{}".format(self.name)

Step3 写入数据

if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    s1 = Student('s1')
    s2 = Student('s2')
    c1 = Course('c1')
    c2 = Course('c2')
    c3 = Course('c3')
    s1.course = [c1, c2, c3]
    s2.course = [c1, c2]
    db.session.add(s1)
    db.session.add(s2)
    db.session.commit()

    # query
    students = Student.query.all()
    print(students)
    for s in students:
        print("Student {} has course:{}".format(s.name, s.course))
    print("\n")

    # delete - 仅解绑Student与Course的数据关系,则从关联中间表tags删除记录即可
    db.session.query(Student).filter(Student.id == 1).first().course.remove(c1)
    db.session.commit()
    students = Student.query.all()
    print(students)
    for s in students:
        print("Student {} has course:{}".format(s.name, s.course))
    print("\n")

    # delete - 删除Student数据,同时关联中间表tags会自动删除相关记录
    stu = db.session.query(Student).filter(Student.id == 1).first()
    db.session.delete(stu)
    db.session.commit()
    students = Student.query.all()
    print(students)
    for s in students:
        print("Student {} has course:{}".format(s.name, s.course))

输出:

[Student's name :s1, Student's name :s2]
Student s1 has course:[Course's name :c1, Course's name :c2, Course's name :c3]
Student s2 has course:[Course's name :c1, Course's name :c2]


[Student's name :s1, Student's name :s2]
Student s1 has course:[Course's name :c2, Course's name :c3]
Student s2 has course:[Course's name :c1, Course's name :c2]


[Student's name :s2]
Student s2 has course:[Course's name :c1, Course's name :c2]
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签