flask-分页、模型对应关系

2018-10-11  本文已影响0人  旧时初_2e8d

一、分页

    page = int(request.args.get('page', 1))
    # 方法一
    stus = Students.query.offset((page - 1) * 2).limit(5)
    # 切片
    stu1 = Students.query.all()[(page - 1) * 2:page * 2]
    # sql语句
    sql = 'select * from students limit %s,%s ' % ((page - 1) * 2, page * 2)
    stu2 = db.session.execute(sql)
    # paginate()方法
    paginates = Students.query.paginate(page, 4)
    stu3 = paginates.items
    return render_template('index.html', stus=stu3, paginates=paginates)

二、模型关系

1.一对多
学生类
class Students(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    s_name = db.Column(db.String(20), unique=False, nullable=False)
    s_age = db.Column(db.Integer, default=19)
    s_g = db.Column(db.Integer, db.ForeignKey('grade.id'), nullable=True)

    __tablename__ = 'students'
班级类
class Grade(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    g_name = db.Column(db.String(30), unique=True, nullable=False)
    students = db.relationship('Students', backref='grade')

    __tablename__ = 'grade'
绑定学生和班级关联关系
    stus_id = [8, 9]
    for id in stus_id:
        stu = Students.query.get(id)
        # 在flask中stu.s_g获取的值为int类型
        # 在django中,stu.s_g获取的是对象,stu.s_g_id获取到的int类型
        stu.s_g = 3
        stu.save()
通过班级查找学生信息
grade = Grade.query.filter(Grade.g_name == '花儿一班').first()
    stus = grade.students
通过学生查找班级信息
 stu = Students.query.get(5)
    # 获取班级,学生对象.backref
    grade = stu.grade
2.多对多
学生类
class Students(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    s_name = db.Column(db.String(20), unique=False, nullable=False)
    s_age = db.Column(db.Integer, default=19)
    s_g = db.Column(db.Integer, db.ForeignKey('grade.id'), nullable=True)

    __tablename__ = 'students'
课程类
class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    g_name = db.Column(db.String(30), unique=True, nullable=False)
    students = db.relationship('Students', secondary=s_c, backref='cou')

    __tablename__ = 'course'
中间表
s_c = db.Table('s_c',
               db.Column('s_id', db.Integer, db.ForeignKey('students.id'), primary_key=True),
               db.Column('c_id', db.Integer, db.ForeignKey('course.id'), primary_key=True))
绑定学生与课程关联关系
stu = Students.query.get(2)
    # 学生对象查找课程信息,stu.cou
    cou1 = Course.query.get(1)
    cou2 = Course.query.get(2)
    # 绑定学生科课程的关联关系
    stu.cou.append(cou1)
    stu.cou.append(cou2)
    stu.save()
上一篇下一篇

猜你喜欢

热点阅读