flask 多對多關係 主從表之間查詢
阿新 • • 發佈:2018-12-14
model層
class Studentnew(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(20),unique=True) #新增多對多的反向引用,必須使用secondary指定中間關聯表 courses = db.relationship('Course', secondary='xuankebiao', backref=db.backref('students', lazy='dynamic'), lazy='dynamic')
class Course(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(20),unique=True) # 學生選課表(中間關聯表),不需要使用者維護 xuankebiao = db.Table('xuankebiao', db.Column('student_id', db.Integer, db.ForeignKey('studentnew.id')), db.Column('course_id', db.Integer, db.ForeignKey('course.id')), )
views函式:
#多對多關係查詢 @blue.route('/manytomany/<id>/') def manytumany(id): #根據學生找課程 # student =Studentnew.query.get(id) # courses = student.courses.all() # return ','.join(c.name for c in courses) #根據課程找學生 course = Course.query.get(id) stus = course.students.all() return ','.join((i.name for i in stus)) #多對多新增刪除 @blue.route('/many_many/') def many_many(): student = Studentnew.query.get(1) course = Course.query.get(5) #學生選課 # student.courses.append(course) # return student.name + '選了' + course.name #取消選課 student.courses.remove(course) return student.name + '取消' + course.name