当前位置:   article > 正文

flask-17 flask-sqlalchemy查询

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

  1. {% extends 'base.html' %}
  2. {% block title %}
  3. 用户登录
  4. {% endblock %}
  5. {% block middle %}
  6. {{ user.username }} ---{{ user.rdatetime }}
  7. <hr>
  8. {{ user1 }}
  9. <hr>
  10. 一共有:{{ user2|length }}个用户
  11. {{ user2 }}
  12. <hr>
  13. 一共有:{{ user3|length }}个用户
  14. {{ user3 }}
  15. <hr>
  16. 一共有:{{ user4|length }}个用户
  17. {{ user4 }}
  18. <hr>
  19. 一共有:{{ user5|length }}个用户
  20. {{ user5 }}
  21. <hr>
  22. 一共有:{{ user6|length }}个用户
  23. {{ user6 }}
  24. {% endblock %}

2、修改apps/user下view.py

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2021/12/16 10:03
  4. # @Author : niubobo
  5. # @File : view.py
  6. # @Software: PyCharm
  7. from flask import Blueprint, request, render_template, redirect,url_for
  8. import hashlib
  9. from sqlalchemy import or_, and_
  10. from apps.user.models import User
  11. from ext import db
  12. user_bp = Blueprint('user', __name__)
  13. @user_bp.route('/')
  14. def user_center():
  15. # 查询数据库中的数据
  16. users = User.query.all()
  17. return render_template('user/center.html', users=users)
  18. @user_bp.route('/register', methods=['GET', 'POST'])
  19. def register():
  20. if request.method == 'POST':
  21. # 获取post提交得数据
  22. username = request.form.get('username')
  23. password = request.form.get('password')
  24. repassword = request.form.get('repassword')
  25. phone = request.form.get('phone')
  26. if password == repassword:
  27. # # 用户唯一
  28. # a 查询所有用户
  29. users = User.query.all()
  30. # b 遍历比较
  31. for user in users:
  32. if user.username == username:
  33. return render_template('user/register.html', msg='用户名已存在')
  34. # 与模型结合
  35. # 1、找到模型类并创建对象
  36. user = User()
  37. # 2、给对象赋值
  38. user.username = username
  39. user.password = hashlib.sha256(password.encode('utf-8')).hexdigest()
  40. user.phone = phone
  41. # 添加
  42. # 3、将user添加到session中(类似缓存)
  43. db.session.add(user)
  44. # 4、提交数据
  45. db.session.commit()
  46. return redirect(url_for('user.user_center'))
  47. else:
  48. return '两次密码不一致'
  49. return render_template('user/register.html')
  50. # return '用户注册'
  51. @user_bp.route('/login', methods=['GET', 'POST'])
  52. def login():
  53. if request.method == 'POST':
  54. username = request.form.get('username')
  55. password = request.form.get('password')
  56. # 因为密码加密所以只能将登录的密码加密然后与数据库的密码进行比对
  57. new_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
  58. # 关键 查询user表当中的的username
  59. # 查询
  60. user_list = User.query.filter_by(username=username)
  61. for u in user_list:
  62. if u.password == new_password:
  63. return '用户登录成功'
  64. else:
  65. return render_template('user/login.html', msg='用户名或者密码错误')
  66. return render_template('user/login.html')
  67. @user_bp.route('/del')
  68. def del_user():
  69. # 获取传递得username
  70. username = request.args.get('username')
  71. # a 查询所有用户
  72. users = User.query.all()
  73. # b 根据username找到列表users当中得user对象
  74. for user in users:
  75. if user.username == username:
  76. # 删除用户
  77. db.session.delete(user)
  78. db.session.commit()
  79. return redirect('/')
  80. else:
  81. return '删除失败'
  82. @user_bp.route('/select')
  83. def query_demo():
  84. user = User.query.get(9) # 根据逐渐查询用户使用get(主键值) 返回值是一个用户对象
  85. # 查询用户名为bocai的第一个对象
  86. user1 = User.query.filter(User.username == 'bocai').first()
  87. # 以b开头的
  88. user2 = User.query.filter(User.username.startswith('b')).all()
  89. # 组合查询1 需要from sqlalchemy import or_
  90. user3 = User.query.filter(or_(User.username.startswith('b'), User.username.contains('t'))).all()
  91. # 组合查询2 需要from sqlalchemy import and_
  92. user4 = User.query.filter(and_(User.username.startswith('b'), User.rdatetime < '2021-12-30 00:00:00')).all()
  93. user5 = User.query.order_by(User.id).limit(2).all()
  94. # 偏移2个用户
  95. user6 = User.query.order_by(User.id).offset(2).limit(2).all()
  96. return render_template('user/select.html', user=user, user1=user1, user2=user2, user3=user3,user4=user4,user5=user5,user6=user6)

3、启动访问服务

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/507790
推荐阅读
相关标签
  

闽ICP备14008679号