Day59 - Flask模型、分页

2018-12-19  本文已影响0人  莫名ypc

定义模型

生成的表明默认为类名

也可以通过__tablename__ = '表名' 自己定义

from flask_sqlalchemy import SQLAlchemy


db = SQLAlchemy()


class Student(db.Model):
    __tablename__ = 'student'  # 默认表名就为student
    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)

迁移方式

通过函数迁移或者在Terminal使用命令迁移

python manage.py shell
>>from ap.models import db
>>db.create_all() 

添加数据

db.session.add()
db.session.commit()

@blue.route('/add/', methods=['GET', 'POST'])
def stu_add():
    if request.method == 'GET':
        return render_template('add.html')

    if request.method == 'POST':
        # 创建学生信息
        # 1.获取数据
        username = request.form.get('username')
        phone = request.form.get('phone')
        age = request.form.get('age')
        # 2.保存
        stu = Student()
        stu.s_name = username
        stu.s_phone = phone
        stu.s_age = age
        db.session.add(stu)
        db.session.commit()
        return redirect(url_for('app.stu_list'))

查询所有

Student.query.all()

查询的结果为列表

@blue.route('/list/', methods=['GET'])
def stu_list():
    students = Student.query.all()
    return render_template('list.html', students=students)

修改数据

通过filter查询到修改对象,filter(Studetn.id == id),查询结果为类表

通过Student.query.filter(Student.id == id).first()获取到查询对象

db.session.add(stu)可以写也可以省略

db.session.commit()

@blue.route('/edit/<int:id>/', methods=['GET', 'POST'])
def stu_edit(id):
    if request.method == 'GET':
        stu = Student.query.filter(Student.id == id).first()
        return render_template('add.html', stu=stu)
    if request.method == 'POST':
        # 1.获取页面中的参数
        username = request.form.get('username')
        age = request.form.get('age')
        phone = request.form.get('phone')
        # 2.获取对象
        stu = Student.query.filter(Student.id == id).first()
        # 3.修改属性
        stu.s_name = username
        stu.s_phone = phone
        stu.s_age = age
        db.session.add(stu)
        db.session.commit()
        return redirect(url_for('app.stu_list'))

删除数据

db.session.delete(对象)

db.session.commit()

@blue.route('/del/<int:id>/', methods=['GET', 'POST'])
def stu_del(id):
    if request.method == 'GET':
        # 获取删除对象
        stu = Student.query.filter(Student.id == id).first()
        # 使用delete(对象)
        db.session.delete(stu)
        db.session.commit()
        return redirect(url_for('app.stu_list'))

批量添加

db.session.add_all(对象)

db.session.commit()

@blue.route('/add_all/', methods=['GET'])
def add_all():
    stus = []
    for i in range(10):
        stu = Student()
        stu.s_age = random.randint(18, 28)
        stu.s_name = '小明%s' % random.randint(0, 10000)
        stu.s_phone = '12345678910'
        stus.append(stu)
        # db.session.add(stu)
    db.session.add_all(stus)
    db.session.commit()
    return '创建成功'

查询

query.filter(模型.字段 == 值)

query.filter_by(字段=值)

query.get(主键值)

stus = Student.query.offset(0).limit(2)
stus = Student.query.filter(Student.s_name.contains('小明')).all()
    stus = Student.query.filter(Student.s_name.startswith('小')).all()
    stus = Student.query.filter(Student.s_name.endswith('3')).all()
    stus = Student.query.filter(Student.s_name.like('___明%')).all()
    stus = Student.query.filter(Student.id.in_([1, 2, 3, 4, 5]))
    stus = Student.query.filter(Student.s_age.__le__(21)).all()
    stus = Student.query.filter(Student.s_age <= 21).all()
suts = Student.query.filter(Student.s_age < 22).filter(Student.s_name.endswith('6')).all()
suts = Student.query.filter(Student.s_age < 22, Student.s_name.endswith('6')).all()
from sqlalchemy import and_, not_, or_

suts = Student.query.filter(and_(Student.s_age < 22, Student.s_name.endswith('6'))).all()

suts = Student.query.filter(or_(Student.s_age < 22, Student.s_name.endswith('6'))).all()

suts = Student.query.filter(not_(Student.s_age == 22)).all()

分页

@blue.route('/list/', methods=['GET'])
def stu_list():
    # students = Student.query.all()
    page = int(request.args.get('page', 1))
    paginate = Student.query.paginate(page=page, per_page=5)
    students = paginate.items
    return render_template('list.html', students=students, paginate=paginate)

list.html

{% extends 'base.html' %}

{% block title %}
    学生列表
{% endblock %}

{% block content %}
    <p><a href="{{ url_for('app.stu_add') }}">添加学生信息</a></p>

    <p>学生信息</p>
    <table>
        <thead>
            <th>id</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>电话</th>
            <th>操作</th>
        </thead>
        <tbody>
            {% for stu in students %}
                <tr>
                    <td>{{ stu.id }}</td>
                    <td>{{ stu.s_name }}</td>
                    <td>{{ stu.s_age }}</td>
                    <td>{{ stu.s_phone }}</td>
                    <td>
                        <a href="{{ url_for('app.stu_edit', id=stu.id) }}">修改</a>
                         |
                        <a href="{{ url_for('app.stu_del', id=stu.id) }}">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    {% if paginate.has_prev %}
        <a href="{{ url_for('app.stu_list') }}?page={{ paginate.prev_num }}">上一页</a>
    {% else %}
        <a href="#">上一页</a>
    {% endif %}

    {% for i in paginate.iter_pages() %}
        <a href="{{ url_for('app.stu_list')}}?page={{ i }}">{{ i }}</a>
    {% endfor %}

    {% if paginate.has_next %}
        <a href="{{ url_for('app.stu_list') }}?page={{ paginate.next_num }}">下一页</a>
    {% else %}
        <a href="#">下一页</a>
    {% endif %}

    当前{{ paginate.page }}页, 共{{ paginate.pages }}页, 一共{{ paginate.total }}条数据
{% endblock %}
上一篇下一篇

猜你喜欢

热点阅读