day04 模型关系

一对多

models.py

**在Flask中模型查询关系不是靠外键是relationship**
**外键建立在多的那方**
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    s_name = db.Column(db.String(20), unique=True,nullable=False)
    s_phone = db.Column(db.String(11),nullable=True)
    s_age = db.Column(db.Integer,nullable=False)
    s_gender = db.Column(db.Integer,default=1)
    grade_id = db.Column(db.Integer,db.ForeignKey('grade.id'),nullable=True)

**relationship建立在一的那方**
class Grade(db.Model):
    __tablename__ = 'grade'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    g_name = db.Column(db.String(10), unique=True, nullable=False)
    stus = db.relationship('Student',backref='g')

views.py

一查多
def sel_st_by_grade():
    # 查询班级python1的学生信息
    grade = Grade.query.filter(Grade.g_name=='python 1').first()
    # 通过班级拿到学生对象 是个列表
    students = grade.stus
    return 'done '


多查一
# 通过学生查班级
@blue.route('/sel_grade_by_st/',methods=['GET','POST'])
def sel_grade_by_st():
    # 查询id=12的学生班级信息
    stu = Student.query.get(12)
    grade=stu.g
    return 'done '

#多对多

多对多

models.py

**多对多relationship定义在任何一方都可以**
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    s_name = db.Column(db.String(20), unique=True,nullable=False)
    s_phone = db.Column(db.String(11),nullable=True)
    s_age = db.Column(db.Integer,nullable=False)
    s_gender = db.Column(db.Integer,default=1)
    grade_id = db.Column(db.Integer,db.ForeignKey('grade.id'),nullable=True)



s_c = db.Table('s_c',
               db.Column('s_id', db.Integer,db.ForeignKey('student.id')),
                db.Column('c_id', db.Integer, db.ForeignKey('course.id'))
               )

class Course(db.Model):
    __tablename__ = 'course'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    c_name = db.Column(db.String(10), unique=True, nullable=False)
    stus = db.relationship('Student',secondary=s_c,backref='cou')

    def save(self):
        db.session.add(self)
        db.session.commit()

添加中间表数据

views.py

@blue.route('/add_middle/',methods=['GET','POST'])
def add_middle():
    给所有学生添加课程id为3的课
    course = Course.query.filter(Course.id == 3).first()
    student = Student.query.filter().all()

    学生查课程 注意必须是一个学生
    student.cou
    课程查询学生
    course.stus

     添加
    for stu in student: 
        course.stus.append(stu)
        #stu.cou.append(course)效果一样
    删除
    for stu in student:
        course.stus.remove(stu)
    db.session.commit()
    return 'done1'

你可能感兴趣的:(day04 模型关系)