如何使用 SQLAlchemy(不是 flask_sqlalchemy 或 flask-merge)将数据插入相互关联的关系表中?

How to inserting data into interrelated relationship tables using SQLAlchemy (not flask_sqlalchemy or flask-merge)?

我是 SQLAlchemy 的新手,我正在尝试使用 SQLAlchemy 构建一个练习项目。我创建了包含具有以下关系的表的数据库。现在我的问题是:

  1. 如何 INSERT 数据到表中,因为它们是相互依赖的?
  2. 这是否形成了数据库设计的循环?
  3. 循环数据库设计是一种不好的做法吗?如果这是一种不好的做法,该如何解决?

    Department.manager_ssn ==> Employee.SSN

    Employee.department_id ==> Department.deptid

database relationship diagram

以下是创建此确切数据库的代码的当前版本。

# Department table
class Departments(Base):
    __tablename__ = "Departments"   

    # Attricutes
    Dname= Column(String(15), nullable=False)
    Dnumber= Column(Integer, primary_key=True)
    Mgr_SSN= Column(Integer, ForeignKey('Employees.ssn'), nullable=False)
    employees = relationship("Employees")

# Employee table
class Employees(Base):
    __tablename__ = "Employees" 

    # Attributes
    Fname = Column(String(30), nullable=False) 
    Minit = Column(String(15), nullable=False)  
    Lname = Column(String(15), nullable=False)  
    SSN = Column(Integer, primary_key=True)
    Bdate = Column(Date, nullable=False)
    Address = Column(String(15), nullable=False)  
    Sex = Column(String(1), default='F', nullable=False)
    Salary = Column(Integer, nullable=False)
    Dno = Column(Integer, ForeignKey('Departments.Dnumber'), nullable=False)
    departments = relationship("Departments")

请仅在 SQLAlchemy 中提供解决方案,而不是在 flask-sqlalchemy 或 flask-migrate 中提供解决方案,我正在使用 Python 3.6.

您可以通过

完全避免这种循环参考设计
  • 仅在关系的一侧声明外键约束
  • 使用布尔标志来表示员工是否是经理
class Department(Base):
    __tablename__ = 'departments'

    department_id = Column(Integer, primary_key=True)
    employees = relationship('Employee', lazy='dynamic', back_populates='department')    


class Employee(Base):
    __tablename__ = 'employees'

    employee_id = Column(Integer, primary_key=True)
    is_manager = Column(Boolean, nullable=False, default=False)
    department_id = Column(Integer, ForeignKey('departments.department_id'), nullable=False)

    department = relationship('Department', back_populates='employees')

您可以使用

找到部门经理
department = session.query(Department).get(..)
department.employees.filter(Employee.is_manager == True).one_or_none()