SQLAlchemy很多关系混乱

时间:2015-03-10 12:47:09

标签: orm sqlalchemy associations

考虑以下模型(来自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"))

我知道这段代码在employees和depts之间建立了很多关系。假设我必须将department_id和employee_id插入到DepartmentEmployee链接表中,我该怎么做?教程说:

>>> 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()

但我想分开做。首先,我想在department表中添加详细信息,然后是employee表。最后,我需要填充Dept-employee链接,用户单独输入extra_data列...我该怎么做? 我尝试过做这样的事情

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个表中的数据,插入链接表?

我在那里学到了一种方法,就像" employees.append.xxx"但我不明白..有人能指出我正确的方向吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

这是使用association_table在SQLAlchemy中定义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()