flask-17 flask-sqlalchemy查询

查询记录

那么我们怎么从数据库中查询数据?为此,Flask-SQLAlchemy 在您的 Model 类上提供了 query 属性。当您访问它时,您会得到一个新的所有记录的查询对象。在使用 all() 或者 first() 发起查询之前可以使用方法 filter() 来过滤记录。如果您想要用主键查询的话,也可以使用 get()

一、查询 示例

1、查询所有:

模型类.query.all()    等价于   select * from user;

2、有条件的查询:

1)模型类.query.filter_by(字段名 =值) 等价于 select * from user where 字段名=值;

2)模型类.query.filter_by(字段名 =值).first() 等价于 select * from user where 字段名=值 limit 1;

1 、模型类.query.filter_by与模型类.query.filter区别

        模型类.query.filter_by(字段名=值) 里面是布尔的条件   这个无法实现复杂查询

         模型类.query.filter(模型类.字段名==值) 里面是布尔的条件   【常用】

 2、模型类.query.filter(模型类.字段名==值使用

         a)模型类.query.filter(模型类.字段名==值) .all()    返回值 --->列表

         b)模型类.query.filter(模型类.字段名==值) .first()   返回值 --->对象

3)模型类.query.filter(模型类.字段名.endswith('z')).all() 等价于 select * from user where 字段名 like '%z';

4)模型类.query.filter(模型类.字段名.startswith('z')).all() 等价于 select * from user where 字段名 like 'z%';

5)模型类.query.filter(模型类.字段名.contains('z')).all() 等价于 select * from user where 字段名 like '%z%';

6)模型类.query.filter(模型类.字段名.like('%z%')).all() 等价于 select * from user where 字段名 like '%z%';

7)模型类.query.filter(模型类.字段名.in_(['a','b','c'])).all() 等价于 select * from user where 字段名  in ('a','b','c');

8)模型类.query.filter(模型类.字段名.between(开始,结束)).all() 等价于 select * from user where 字段名  between 开始 and  结束;

3、组合查询

需要导入

from sqlalchemy import or_, and_, not_

1)模型类.query.filter(or_(模型类.字段名.like('z%'),模型类.字段名.contains('a'))).all() 等价于 select * from user where 字段名 like 'z%' or 字段名 like '%a%';

2)模型类.query.filter(and_(模型类.字段名.like('z%'),模型类.字段名 < '2021-12-12 00:00:00')).all() 等价于 select * from user where 字段名 like 'z%' and 字段名 < '2021-12-12 00:00:00';

  修改 < 为 __it__   

模型类.query.filter(and_(模型类.字段名.like('z%'),模型类.字段名.__lt__( '2021-12-12 00:00:00'))).all() 等价于 select * from user where 字段名 like 'z%' and 字段名 < '2021-12-12 00:00:00';

扩展

>       __gt__ 

 >=     __ge__(gt equal)

<=     __le__(lt euqal)

!=      not_

3)模型类.query.filter(not_(模型类.字段名.contains('a'))).all() 等价于 select * from user where 字段名  not like '%a%' ;

二、排序order_by

1、无条件的排序

模型类.query.order_by (模型类.字段名.desc()).all() 等价于 select * from user order by 字段名 desc;

2、有条件的排序

模型类.query.filter(模型类.字段名==值).order_by (模型类.字段名.desc()).all() 等价于 select * from user where  字段名=值 order by 字段名 desc;

也可以这样写

模型类.query.filter(模型类.字段名==值).order_by (-模型类.字段名).all() 等价于 select * from user where  字段名=值 order by 字段名 desc;

三、限制(获取指定数量数据) limit+offset

1、limit

模型类.query.order_by (模型类.字段名).limit(2).all() 等价于 select * from user where  字段名=值 order by 字段名 limit(2);

2、limit+offset 

跳过前2位再取值前两位 就是3、4

模型类.query.order_by (模型类.字段名).offset(2).limit(2).all() 

四、操作

在教程

flask-16 实现登录以及删除更新用户

基础上修改

1、templates/user下新增select.html

{% extends 'base.html' %}
{% block title %}
    用户登录
{% endblock %}
{% block middle %}
    {{ user.username }} ---{{ user.rdatetime }}
    <hr>
    {{ user1 }}
    <hr>
    一共有:{{ user2|length }}个用户
    {{ user2 }}
    <hr>
    一共有:{{ user3|length }}个用户
    {{ user3 }}
    <hr>
    一共有:{{ user4|length }}个用户
    {{ user4 }}
    <hr>
    一共有:{{ user5|length }}个用户
    {{ user5 }}
        <hr>
    一共有:{{ user6|length }}个用户
    {{ user6 }}
{% endblock %}

2、修改apps/user下view.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/16 10:03
# @Author  : niubobo
# @File    : view.py
# @Software: PyCharm
from flask import Blueprint, request, render_template, redirect,url_for
import hashlib

from sqlalchemy import or_, and_

from apps.user.models import User
from ext import db

user_bp = Blueprint('user', __name__)


@user_bp.route('/')
def user_center():
    # 查询数据库中的数据
    users = User.query.all()
    return render_template('user/center.html', users=users)


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # 获取post提交得数据
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        if password == repassword:
            # # 用户唯一
            # a 查询所有用户
            users = User.query.all()
            # b 遍历比较
            for user in users:
                if user.username == username:
                    return render_template('user/register.html', msg='用户名已存在')
            # 与模型结合
            # 1、找到模型类并创建对象
            user = User()
            # 2、给对象赋值
            user.username = username
            user.password = hashlib.sha256(password.encode('utf-8')).hexdigest()
            user.phone = phone
            # 添加
            # 3、将user添加到session中(类似缓存)
            db.session.add(user)
            # 4、提交数据
            db.session.commit()
            return redirect(url_for('user.user_center'))
        else:
            return '两次密码不一致'
    return render_template('user/register.html')
    # return '用户注册'


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 因为密码加密所以只能将登录的密码加密然后与数据库的密码进行比对
        new_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        # 关键 查询user表当中的的username
        # 查询
        user_list = User.query.filter_by(username=username)
        for u in user_list:
            if u.password == new_password:
                return '用户登录成功'
            else:
                return render_template('user/login.html', msg='用户名或者密码错误')

    return render_template('user/login.html')


@user_bp.route('/del')
def del_user():
    # 获取传递得username
    username = request.args.get('username')
    # a 查询所有用户
    users = User.query.all()
    # b 根据username找到列表users当中得user对象
    for user in users:
        if user.username == username:
            # 删除用户
            db.session.delete(user)
            db.session.commit()
            return redirect('/')
    else:
        return '删除失败'


@user_bp.route('/select')
def query_demo():
    user = User.query.get(9)  # 根据逐渐查询用户使用get(主键值) 返回值是一个用户对象
    # 查询用户名为bocai的第一个对象
    user1 = User.query.filter(User.username == 'bocai').first()
    # 以b开头的
    user2 = User.query.filter(User.username.startswith('b')).all()
    # 组合查询1 需要from sqlalchemy import or_
    user3 = User.query.filter(or_(User.username.startswith('b'), User.username.contains('t'))).all()
    # 组合查询2 需要from sqlalchemy import and_
    user4 = User.query.filter(and_(User.username.startswith('b'), User.rdatetime < '2021-12-30 00:00:00')).all()
    user5 = User.query.order_by(User.id).limit(2).all()
    # 偏移2个用户
    user6 = User.query.order_by(User.id).offset(2).limit(2).all()
    return render_template('user/select.html', user=user, user1=user1, user2=user2, user3=user3,user4=user4,user5=user5,user6=user6)

3、启动访问服务

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值