[英]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. 我是SQLAlchemy的新手,我正在尝试使用SQLAlchemy构建实践项目。 I have created the database containing tables with the following relationship.
我创建了包含具有以下关系表的数据库。 Now my questions are :
现在我的问题是:
Is the looping database design, a bad practice? 循环数据库设计是不好的做法吗? How to resolve this if its a bad practice?
如果这是错误的做法,该如何解决?
Department.manager_ssn ==> Employee.SSN Department.manager_ssn ==> Employee.SSN
and 和
Employee.department_id ==> Department.deptid 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. 请仅在SQLAlchemy中提供解决方案,而不在flask-sqlalchemy或flask-migrate中提供解决方案,并且我正在使用Python 3.6。
You can avoid such circular reference design altogether by 您可以通过以下方式完全避免此类循环参考设计
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.