簡體   English   中英

如何使用SQLAlchemy(而不是flask_sqlalchemy或flask-merge)將數據插入到相關的關系表中?

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

我是SQLAlchemy的新手,我正在嘗試使用SQLAlchemy構建實踐項目。 我創建了包含具有以下關系表的數據庫。 現在我的問題是:

  1. 如何將數據插入到表中,因為它們是相互依存?
  2. 這會在數據庫設計中形成一個循環嗎?
  3. 循環數據庫設計是不好的做法嗎? 如果這是錯誤的做法,該如何解決?

    Department.manager_ssn ==> Employee.SSN

    Employee.department_id ==> Department.deptid

數據庫關系圖

以下是創建此確切數據庫的當前代碼版本。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM