from sqlalchemy import Integer, Column, String, ForeignKey, DateTime, func from sqlalchemy.orm import declarative_base, relationship, backref, sessionmaker from sqlalchemy import create_engine Base = declarative_base() class Department(Base): __tablename__ = 'department' id = Column(Integer, primary_key=True) name = Column(String) city = Column(String) class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String) hired_on = Column(DateTime, default=func.now()) department_id = Column(Integer, ForeignKey('department.id')) department = relationship(Department, backref=backref('employees', uselist=True, cascade='delete,all')) age = Column(Integer) engine = create_engine("sqlite:///") session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) s = session() it_department = Department(name='IT') financial_department = Department(name='Finance') financial_department.city = 'Beijing' s.add(financial_department) print(s.query(Department).count()) for department in s.query(Department).all(): print(department.name, department.city) s.delete(department) print(s.query(Department).count())