Flask-表的多对多关系

多对多的关系,一般都是拆分成两张一对多的表

代码演示:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/database01'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
app.app_context().push()
#中间表
db.Table(
    "tb_student_course",
    db.Column("student_id", db.Integer,db.ForeignKey("students.id")),
    db.Column("course_id", db.Integer,db.ForeignKey("courses.id"))
)

class Student(db.Model):
    __tablename__ = 'students'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(32))
    # 关系属性secondary使用在多对多中,表示二次查询
    courses = db.relationship("Course",backref='students',secondary='tb_student_course')

    #为了方便输出对象查看,重写__repr__方法
    def __repr__(self):
        return ""%self.name

class Course(db.Model):
    __tablename__ = "courses"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32))

    def __repr__(self):
        return ""%self.name

if __name__ == "__main__":
    db.drop_all()
    db.create_all()

    # 添加数据
    stu1 = Student(name='牛大')
    stu2 = Student(name='牛二')
    stu3 = Student(name='牛三')

    cou1 = Course(name='数学')
    cou2 = Course(name='语文')
    cou3 = Course(name='英语')

    stu1.courses = [cou1, cou2]
    stu2.courses = [cou3]
    stu3.courses = [cou2, cou3]
    db.session.add_all([stu1,stu2,stu3])
    db.session.add_all(([cou1,cou2,cou3]))

    db.session.commit()

    app.run(debug=True)

你可能感兴趣的:(Flask,flask,python,数据库,后端)