ryentzer

sqlalchemy

Nov 24th, 2020
673
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from sqlalchemy import Column, String, Integer, ForeignKey
  2. from sqlalchemy.orm import relationship, sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy import create_engine
  5.  
  6. Base = declarative_base()
  7.  
  8.  
  9. class Department(Base):
  10.     __tablename__ = 'department'
  11.     id = Column(Integer, primary_key=True)
  12.     name = Column(String)
  13.     employees = relationship('Employee', secondary='department_employee')
  14.  
  15.  
  16. class Employee(Base):
  17.     __tablename__ = 'employee'
  18.     id = Column(Integer, primary_key=True)
  19.     name = Column(String)
  20.     departments = relationship('Department', secondary='department_employee')
  21.  
  22.  
  23. class DepartmentEmployee(Base):
  24.     __tablename__ = 'department_employee'
  25.     department_id = Column(Integer, ForeignKey('department.id'), primary_key=True)
  26.     employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
  27.  
  28.  
  29. engine = create_engine('sqlite:///department_store2.db')
  30. session = sessionmaker()
  31. session.configure(bind=engine)
  32. # Base.metadata.create_all(engine)
  33.  
  34. s = session()
  35. m = s.query(Employee).filter(Employee.name == 'Mary').one()
  36. i = s.query(Department).filter(Department.name == 'IT').one()
  37.  
  38. s.delete(m.departments.filter(Department.name == 'IT'))
  39. s.add(m)
  40. s.commit()
RAW Paste Data