sqlalchemy--m2m
这一块先建个表, 后面再讨论
# -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, String, Integer, ForeignKey, UniqueConstraint from sqlalchemy.orm import sessionmaker, relationship engine = create_engine("sqlite:///test_s1.db") # 创建数据库连接 session =sessionmaker(bind=engine)() # 创建表 Base = declarative_base() class Student(Base): __tablename__ = 'student' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) class Course(Base): __tablename__ = 'course' id = Column(Integer, primary_key=True) title = Column(String(32), index=True, nullable=False) class Student2Course(Base): __tablename__ = 'student2course' id = Column(Integer, primary_key=True) student_id = Column(Integer, ForeignKey('student.id')) course_id = Column(Integer, ForeignKey('course.id')) __table_args__ = ( UniqueConstraint('student_id', 'course_id', name='uix_st_cou'), ) def create_all(): Base.metadata.create_all(engine) def drop_all(): Base.metadata.drop_all(engine) if __name__ == '__main__': create_all() session.close()