django列表篩選功能的實現(xiàn)代碼
views,中設(shè)置請求的類型
class LawDetailView(View): def get(self, request, law_id): type = request.GET.get('type', '') law = Law.objects.get(id=law_id) return render(request, 'zcfg-detail.html', { 'law': law, 'type': type, })
templates,中設(shè)置:
<div class="col-lg-12" style="margin-bottom: 20px;"> <a class="{% if type == '' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=" rel="external nofollow" role="button">全部</a> <a class="{% if type == 'fl' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=fl" rel="external nofollow" role="button">法律</a> <a class="{% if type == 'xzfg' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=xzfg" rel="external nofollow" role="button">行政法規(guī)</a> <a class="{% if type == 'bmgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=bmgz" rel="external nofollow" role="button">部門規(guī)章</a> <a class="{% if type == 'dfgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=dfgz" rel="external nofollow" role="button">地方規(guī)章</a> </div>
補充知識:django 一種動態(tài)查詢的便捷實現(xiàn)過程
問題引出
你可能遇到這種情況,在前端頁面上有查詢功能,要查詢的輸入選擇有A,B,C等,可以通過任意一個查詢,或者任意組合進行查詢。
在后端,你可以使用request.GET['A']獲取傳入的數(shù)值。
我們需要判斷哪個有輸入,再在數(shù)據(jù)庫中進行查詢,這樣比較麻煩。
解決方案
動態(tài)實現(xiàn)查詢過程
kwargs = {} if A is not None: kwargs['name__startWith'] = A if B is not None: kwargs['address__contains'] = B if C is not None: kwargs['mobile__endWith'] = C ... ... personList = Person.objects.filter(**kwargs) ...
注:
A B C 等,為前端傳輸過來的數(shù)據(jù)
name address mobile 等,需為你要查詢的表的屬性字段
startWith contains endWith 等,為你要篩選的規(guī)則
Person 為model 表名
以上這篇django列表篩選功能的實現(xiàn)代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Django框架的rest_framework的身份驗證和權(quán)限解析
Django 是一個基于 Python 的 Web 框架,可讓您快速創(chuàng)建高效的 Web 應(yīng)用程序,這篇文章主要介紹了基于Django框架的rest_framework的身份驗證和權(quán)限解析,需要的朋友可以參考下2023-05-05簡單介紹Python中的try和finally和with方法
這篇文章主要介紹了Python中的try和finally和with方法,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05Python編寫可視化界面的全過程(Python+PyCharm+PyQt)
這篇文章主要給大家介紹了關(guān)于Python編寫可視化界面的相關(guān)資料,主要使用了Python+PyCharm+PyQt,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-05-05基于Pydantic封裝的通用模型在API請求驗證中的應(yīng)用詳解
這篇文章主要介紹了基于Pydantic封裝的通用模型在API請求驗證中的應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2023-05-05