简体   繁体   中英

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

I am new to SQLAlchemy, I am trying to build a practice project using SQLAlchemy. I have created the database containing tables with the following relationship. Now my questions are :

  1. How to INSERT data into the tables as they are interdependent?
  2. Does this form a loop in database design?
  3. Is the looping database design, a bad practice? How to resolve this if its a bad practice?

    Department.manager_ssn ==> Employee.SSN
    and
    Employee.department_id ==> Department.deptid

database relationship diagram

and following is the current version of code creating this exact database.

# 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")

Please provide the solution in SQLAlchemy only and not in flask-sqlalchemy or flask-migrate and I am using Python 3.6.

You can avoid such circular reference design altogether by

  • Declaring the foreign key constraint on just one side of the relationship
  • Use a boolean flag to denote if the employee is a manager
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')

You can find the manager of the department using

department = session.query(Department).get(..)
department.employees.filter(Employee.is_manager == True).one_or_none()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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