django是有orm操作的 可想而知 那么flask也是有orm操作的,其實flask的orm操作的使用和djnago的是差不多的
django的orm操作進行條件篩選的時候后面跟着的是objects
django
表名.objects.語句
flask的是query
表名.objects.語句
eg:
django:
User.objects.filter(條件).first
flask:
User.query.filter_by(條件).first
常用查詢語句:
all() 查詢所有 filter_by / filter 單個查詢 filter_by 不需要指定是哪個類的哪個屬性,只需要制定屬性及其目標值就可以了, 並且只能寫具體的值不能寫模糊值 filter filter中指定查詢條件的時候需要指定類名的前綴。可以指定模糊值 order_by 排序
查詢集
- 原始查詢集
類名.query得到的結果就為原始查詢集
- 數據查詢集
加上各種的過濾器的方法 最終返回的結果 為數據查詢集 都使用數據查詢集
過濾器
(1) all 查詢所有 以列表形式返回 不支持連貫操作
類名.query.all()
User.query.all() # 查詢User表中的所有數據
(2) filter() 過濾
類名.query.filter([類名.屬性名 條件操作符 值])
User.query.filter() #返回所有 User.query.filter(User.age>20) #查詢年齡大於20的數據 User.query.filter(User.age>20,User.age<40) #查詢年齡大於20的數據 and 小於40
(3) filter_by 只支持參數為關鍵字參數
類名.query.filter_by(屬性名=值...)
data = User.query.filter_by(id=2) data = User.query.filter_by(id>2) #錯誤寫法 不可以使用模糊查到 data = User.query.filter_by(id=2,age=27)
(4) offset 偏移量
offset(num)
User.query.filter().offset(2)
(5) limit 取值
limit(num)
User.query.filter(User.age>30).limit(2) 查到的結果只取兩個
(6) offset和limit組合使用
User.query.offset(2).limit(2) 也是只取兩個
(7) order_by() 排序
默認是升序
data = User.query.order_by(User.age) #升序
data = User.query.order_by(-User.age) #降序
(8) first 取出第一條數據 返回對象
User.query.first() == User.query.get(2)
(9) get 獲取id對應的數據
查詢成功返回對象 查詢失敗 返回None
User.query.get(2)
(10) contains 包含關系
User.query.filter(User.username.contains('7')) #username中包含數字7的數據
(11) like 模糊查詢
User.query.filter(User.username.like('李%')) #以李作為開頭的
(12) startswith endswith 以...開頭 以...結尾
User.query.filter(User.username.startswith('李')) # 以姓李的開頭 User.query.filter(User.username.endswith('6')) # 以6為結尾的
(13) 比較運算符
__gt__
__ge__
__lt__
__le__
>
<
>=
<=
==
!=
.
(14) in 和 not in
User.query.filter(User.age.in_([27,12,1,30,40,50]))
(15) is null
User.query.filter(User.username.isnot(None))
(16) and_
多個條件 用逗號隔開,為and操作
from sqlalchemy import and_
User.query.filter(and_(User.age==27,User.id==2))
(17) or_
from sqlalchemy import or_
@main.route('/and/') def myAnd(): data = User.query.filter(or_(User.age==27,User.id==2)) data = User.query.filter(and_(User.username.like('%6%')),or_(User.age>=27,User.id==2)) return render_template('show.html',data=data)
(18) not_
from sqlalchemy import not_
@main.route('/and/') def myAnd(): # data = User.query.filter(not_(User.age>27,User.id==1))\ #錯誤寫法只能給一個條件取反 data = User.query.filter(not_(User.age>27)) return render_template('show.html',data=data)
(19) count 統計
data = User.query.filter(not_(User.age>27)).count()
四、文件的遷移
模塊:
pip install flask-migrate
pip install flask-script
使用
(1) 實例化
from flask_migrate import Migrate,MigrateCommand from flask_sqlalchemy import SQLalchemy app = Flask(__name__) db = SQLalchemy(app) migrate = Migrate(app,db=db) manager = Manager(app) manager.add_command('db',MigrateCommand)
(2) 初始化 遷移文件目錄
python manage.py db init
(3) 生成遷移文件
python manage.py db migrate
(4) 執行遷移文件
python manage.py db upgrade
注意
如果當前存在 模型 但是執行創建遷移文件的時候 提示沒有任何改變的時候 需要查看當前的模型類是否有使用(導入)