SQLAlchemy - 修改现有实体之间的多对多关系

时间:2017-08-25 15:44:34

标签: python sqlalchemy

我有两个具有多对多关系的实体,定义如下:

teacher_student = Table('teacher_student', Base.metadata,
   Column('teacher_id', Integer, ForeignKey('teacher.id')),
   Column('student_id', Integer, ForeignKey('student.id')))

class Teacher(Base):
    __tablename__ = 'teacher'
    id = Column(Integer, primary_key=True, autoincrement=False)
    students = relationship('Student', secondary=teacher_student, 
                            back_populates="teachers")

class Student(Base):
    __tablename__ = 'student'
    id = Column(Integer, primary_key=True, autoincrement=False)
    teachers = relationship('Teacher', secondary=teacher_student, 
                            back_populates="students")

我有一群"老师"和#34;学生"坚持,我想更新他们之间的关系。例如,我想查找现有教师,然后删除并添加一些现有学生(实际上不影响student表)。如果没有SQL炼金术试图为添加的学生执行插入操作(这会导致完整性异常),我无法弄清楚如何执行此操作。

以下是我的尝试:

with session() as session:
    teacher = session.query(Teacher)\
                     .filter_by(id=1)\
                     .first()

    teacher.students.append(Student(id=1))

我错过了什么?

0 个答案:

没有答案