24 lines
1.3 KiB
Python
24 lines
1.3 KiB
Python
|
|||
|
|
|
||
|
|
from sqlalchemy import Column, Integer, Date # 导入"列"和字段类型(整数、日期)
|
||
|
|
from sqlalchemy.orm import relationship # 导入"关系"函数,用来定义表间关联
|
||
|
|
from sqlalchemy_fastapi_demo_1.database import Base # 导入database.py里的Base基类
|
||
|
|
|
||
|
|
|
||
|
|
class Classinfo(Base):# 定义ORM模型类,继承Base,SQLAlchemy才知道它对应一张表
|
||
|
|
# 表名必须和建表语句一致:c_lass
|
||
|
|
__tablename__ = "c_lass" # 指定表名,必须和MySQL里的表名一模一样,否则连不上表
|
||
|
|
|
||
|
|
class_id = Column(Integer, primary_key=True, index=True) # 主键列:整数类型;index=True表示建索引,按这个字段查会更快
|
||
|
|
start_time = Column(Date, nullable=False) # 开班日期:日期类型;nullable=False = 不能为空(数据库层面强制)
|
||
|
|
# 逻辑删除:0未删除,1已删除,默认0
|
||
|
|
is_deleted = Column(Integer, nullable=False, default=0)
|
||
|
|
|
||
|
|
# 反向关系:Student.my_class / Teacher.classes 的对端
|
||
|
|
students = relationship("Student", back_populates="my_class")
|
||
|
|
# 声明关系:一个班级下有很多学生(一对多)。"Student"是字符串,指向学生模型
|
||
|
|
# back_populates="my_class":和Student模型里的my_class属性互相呼应
|
||
|
|
teachers = relationship("Teacher", back_populates="classes")
|
||
|
|
# 同样:一个班级下有很多老师
|
||
|
|
|