1. 程式人生 > 程式設計 >django列表篩選功能的實現程式碼

django列表篩選功能的實現程式碼

views,中設定請求的型別

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,中設定:

<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">行政法規</a>
    <a class="{% if type == 'bmgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=bmgz" rel="external nofollow" role="button">部門規章</a>
    <a class="{% if type == 'dfgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=dfgz" rel="external nofollow" role="button">地方規章</a>
</div>

補充知識:django 一種動態查詢的便捷實現過程

問題引出

你可能遇到這種情況,在前端頁面上有查詢功能,要查詢的輸入選擇有A,B,C等,可以通過任意一個查詢,或者任意組合進行查詢。

在後端,你可以使用request.GET['A']獲取傳入的數值。

我們需要判斷哪個有輸入,再在資料庫中進行查詢,這樣比較麻煩。

解決方案

動態實現查詢過程

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 等,為前端傳輸過來的資料

name address mobile 等,需為你要查詢的表的屬性欄位

startWith contains endWith 等,為你要篩選的規則

Person 為model 表名

以上這篇django列表篩選功能的實現程式碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。