简体   繁体   中英

How to update on Flask-SQLAlchemy association table?

I have a models like this:

taught_courses = db.Table(
    'taught_courses',
    db.Column('teacher_id', db.Integer(), db.ForeignKey('teacher.id')),
    db.Column('course_id', db.Integer(), db.ForeignKey('course.id')),
)

class Teacher(db.Model):
    __tablename__ = 'teacher'
    id = db.Column(db.Integer, primary_key=True)
    taught_courses = db.relationship('Course', secondary=taught_courses, lazy='subquery',
                                     backref=db.backref('courses', lazy=True))
    # ...
    # ...

class Course(db.Model):
    __tablename__ = 'course'
    id = db.Column(db.Integer, primary_key=True)
    # ...
    # ...

And here is how I insert the data to the database:

teacher = Teacher(
    name=form.first_name.data,
    email=form.email.data)
    db.session.add(teacher)

taught_courses = ['Tahsin', 'Arabic Language']   # in the actual case I use this dynamically.

course_id = db.session.query(Course.id).filter(Course.name.in_(taught_courses)).all()

for data in course_id:
    course = Course.query.filter_by(id=data).first()
    course.courses.append(teacher)
    db.session.add(course)
    db.session.commit()

And here is how it look like in the database:

在此处输入图片说明

That is for insert, now I want to make a update able.

In the other example, I want to make it look like this in Flask Admin , where we can update the role in easy way.

在此处输入图片说明

So the point of my question is, how to update record in the association table..?

I figured out this by imagine the case in this answer .

So, in the case of my question, I figured this using the line below:

current_course_name_from_db = ['Tahsin', 'Arabic Language'] # in the actual case I use this dynamically.
want_to_edit_course_with = ['Tahsin']                       # in the actual case I use this dynamically.

course_id_1 = db.session.query(Course.id).filter(Course.name.in_(current_course_name_from_db)).all()
course_id_2 = db.session.query(Course.id).filter(Course.name.in_(want_to_edit_course_with)).all()

for data in course_id_1:
    course = Course.query.filter_by(id=data).first()
    course.courses.remove(teacher)
    db.session.commit()

for data in course_id_2:
    course = Course.query.filter_by(id=data).first()
    course.courses.append(teacher)
    db.session.commit()

So the first thing that I do is, remove all of the course on database, and then make a looping again to append the new value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM