Q 對象
用來匹配資料庫欄位後回傳
# 引入
from django.db.models import Q# 匹配方法#返回匹配得對象
Model.objects.filter(**kwargs)#返回不匹配的對象
Model.objects.exclude(**kwargs)
修改 view
blog = Post.objects.filter(Q(title__contains=get_search) | Q(content__contains=get_search)).order_by('-id')
解析:透過 filter 過濾出符合的對象
條件:title__contains=get_search
格式:’資料庫欄位’ + ‘__contains’ 回傳此欄位有包含 get_search 的所有對象
contains:是否包含(icontains 不區分大小寫)運算邏輯
AND(&), OR(|), NOT(~)
(Q(title__contains=get_search) | Q(content__contains=get_search))
進階用法:operator、reduce
把需要過濾的存到一個變數裡,後續直接在此變數上加上運算邏輯
set_search = [Q(title__contains=get_search), Q(content__contains=get_search)]
加入運算邏輯
#OR
Post.objects.filter(reduce(operator.or_, set_search))#AND
Post.objects.filter(reduce(operator.and_, set_search))
想了解更多可以參考
📌有一個問題還沒解決:render 後網址列沒有改變
還可以改進的地方:
如果沒有 search 到返回上一次頁面所顯示的資料(blog)
1. 改成使用 ajax 傳 ‘blog’ 參數到後端,
django-haystack
等之後用到再補上