1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| from sqlalchemy import Table, Column, Integer, Float, Numeric, String, DateTime, Date, Time, Boolean from sqlalchemy import PrimaryKeyConstraint, ForeignKey, Index, UniqueConstraint from sqlalchemy import text, func, and_, or_, not_, asc, inspect, desc, distinct from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base
from utils.db_ import ModelBase, init_engine, exit_engine, get_engine, session_scope, to_jsonable
Base = declarative_base(cls=ModelBase)
class Clazz(Base): id = Column(Integer(), primary_key=True, autoincrement=True) enroll_year = Column(Integer(), comment="入学年份")
class Student(Base): __table_args__ = ( UniqueConstraint('clazz_id', 'name'), Index('ix_clazz_id_stu_no', 'clazz_id', 'stu_no'), ) id = Column(Integer(), primary_key=True, autoincrement=True) stu_no = Column(String(), index=True, unique=True, comment="学号") name = Column(String(), nullable=True, comment="姓名") clazz_id = Column(Integer(), ForeignKey('clazz.id', ondelete='RESTRICT'), nullable=True, comment="班级ID")
clazz = relationship('Clazz')
class Course(Base): id = Column(Integer(), primary_key=True, autoincrement=True) name = Column(String(), comment="课程名")
students = relationship('Student', secondary='student_course', backref=backref('courses'))
def keys(self): return super().keys() + ["students",]
student_course = Table('student_course', Base.metadata, Column('student_id', Integer(), ForeignKey('student.id'), primary_key=True), Column('course_id', Integer(), ForeignKey('course.id'), primary_key=True))
def main(): engine = init_engine(url=r"sqlite:///:memory:") Base.metadata.create_all(engine) with session_scope() as session: clazz = Clazz(enroll_year=2022) session.add(clazz) session.flush() session.refresh(clazz) print(clazz)
course = Course(name="数学") session.add(course) session.flush() course = session.query(Course).filter(Course.name=="数学").first() print(course)
student = Student(stu_no="007", name="张三", clazz_id=clazz.id) student.courses.append(course) session.add(course) session.flush()
session.refresh(course) print(course.students) print(to_jsonable(course))
student.name = "李四" session.flush()
r = session.execute("select id, name from student").fetchall() for e in r: print(e)
if __name__ == '__main__': main()
|