SQLAlchemy 多对多关系混淆

SQLAlchemy many to many relationships confusion

考虑以下模型(来自 pythoncentral 教程):

class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    employees = relationship(
        'Employee',
        secondary='department_employee_link'
    )


class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    hired_on = Column(DateTime, default=func.now())
    departments = relationship(
        Department,
        secondary='department_employee_link'
    )


class DepartmentEmployeeLink(Base):
    __tablename__ = 'department_employee_link'
    department_id = Column(Integer, ForeignKey('department.id'), primary_key=True)
    employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    extra_data = Column(String(256))
    department = relationship(Department, backref=backref("employee_assoc"))
    employee = relationship(Employee, backref=backref("department_assoc"))

我明白这段代码在员工和 depts.Suppose 之间建立了多对多的关系,我必须将 department_id 和 employee_id 插入 DepartmentEmployee link table,我该怎么做??教程说:

>>> IT = Department(name="IT")
>>> John = Employee(name="John")
>>> John_working_part_time_at_IT = DepartmentEmployeeLink(department=IT, employee=John, extra_data='part-time')
>>> s = session()
>>> s.add(John_working_part_time_at_IT)
>>> s.commit()

但是我想单独做。首先,我想将详细信息添加到部门 table,然后是员工 table。最后,我需要填充用户单独输入 extra_data 列的 Dept-employee link ...我该怎么做? 我试过这样做

def mapper:
    que=DBSession.query(Department)
    que2=DBSession.query(Strings)


                        rel=DepartmentEmployeeLink(extra_data=str(x))//__init__ed this
                        rel.department=que
                        rel.employee=que.employees[0].id

            DBSession.add(rel)

这就是我希望插入的方式,因为我已经在部门和员工内部拥有数据。谁能告诉我如何完成此操作,即如果我在其他 2 table 中有数据,则插入 link table?

我知道有一种方法可以像 "employees.append.xxx" 那样做到这一点,但我不明白..有人能给我指出正确的方向吗?提前致谢。

这是在 SQLAlchemy 中使用 association_table 定义 Many to Many relationship 的更好方法。

association_table = Table('department_employee_link', Base.metadata,
    Column('departmant_id', Integer, ForeignKey('department.id')),
    Column('employee_id', Integer, ForeignKey('employee.id'))
)


class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    employees = relationship(
        'Employee',
        secondary=association_table
    )


class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    hired_on = Column(DateTime, default=func.now())
    departments = relationship(
        Department,
        secondary=association_table
    )


IT = Department(name="IT")
John = Employee(name="John")
IT.employees.append(John)
s = session()
s.add(IT)
s.commit()