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


i new sqlalchemy, trying build practice project using sqlalchemy. have created database containing tables following relationship. questions :

  1. how insert data tables interdependent?
  2. does form loop in database design?
  3. is looping database design, bad practice? how resolve if bad practice?

    department.manager_ssn ==> employee.ssn
    and
    employee.department_id ==> department.deptid

database relationship diagram

and following current version of code creating 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 solution in sqlalchemy , not in flask-sqlalchemy or flask-migrate , using python 3.6.

you can avoid such circular reference design altogether by

  • declaring foreign key constraint on 1 side of relationship
  • use boolean flag denote if employee 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 manager of department using

department = session.query(department).get(..) department.employees.filter(employee.is_manager == true).one_or_none() 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -