Flask-SQLAlchemy常用方法

常用查詢方法

all()返回所有記錄

Note.query.all()

first()返回第一條記錄,沒有返回None
first_or_404()返回第一個條記錄,沒有返回404錯誤響應

Note.query.first()
Note.query.first_or_404()

get()返回指定主鍵值(id字段)的記錄
get_or_404返回指定主鍵值(id字段)的記錄,沒有返回404錯誤響應

Note.query.get(1)
Note.query.get_or_404(1)

count()返回記錄的數量

Note.query.count()

paginate()返回一個Pagination對象,可以對記錄進行分頁處理

Comment.query.order_by(Comment.timestamp.desc()).paginate(page, per_page)
# page:當前頁
# per_page:每頁記錄數

with_parent(instance)傳入模型類實例作爲參數,返回和這個實例相關聯的對象

post = Post.query.get(2)
comment = Comment.query.with_parent(post).filter(Comment.post_id==post.id).first_or_404()

常用過濾方法

filter()使用指定的規則過濾記錄,返回新產生的查詢對象

Note.query.filter(Note.title =='flask').first()

# 除了‘==’和'!='外,其他常用操作符 LIKE、IN、NOTIN、AND、OR等
LIKE:
filter(Note.content like('%foo%'))

IN:
filter(Note.content in_(['foo','bar','baz']))

NOTIN:
filter(~Note.content in_(['foo','bar','baz']))

AND:
from sqlalchemy import and_
filter(and_(Comment.author_id == 1, Comment.is_accept == True))
或者:多個表達式中間用逗號隔開
filter(Comment.author_id == 1, Comment.is_accept == True)
或者:調用多個filter
filter(Comment.author_id == 1).filter(Comment.is_accept == True)

OR:
from sqlalchemy import or_
filter(or_(Comment.author_id == 1, Comment.is_accept == True))

filter_by()使用指定規則過濾記錄(以關鍵字表達式的形式),返回新產生的查詢對象

Note.query.filter_by(title='flask').first()

order_by()根據指定規則排序

Note.query.filter(Note.title = 'flask').order_by(Note.timestamp).all()

limit(limit)根據指定的值限制查詢數量

Comment.query.limit(5).all()

group_by()根據條件對記錄進行分組

from sqlalchemy import func
Comment.query.with_entities(Comment,func.count('*').label('cnt')).group_by(Comment.post_id).all()

offset(offset)根據指定偏移量查詢結果

Comment.query.offset(2).limit(5).all()

記錄一下,如有錯誤請指出,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章