简体   繁体   English

如何更新Flask-SQLAlchemy关联表?

[英]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. 在另一个示例中,我想使它在Flask Admin中看起来像这样,在这里我们可以轻松地更新角色。

在此处输入图片说明

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. 因此,我要做的第一件事是,删除数据库上的所有课程,然后再次循环以追加新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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