Django框架之views(業務邏輯)簡單後臺首頁展示的業務邏輯詳細描述

from django.shortcuts import render,HttpResponse,HttpResponseRedirect

import models
from django.db.models import Q  # 模糊查詢使用的對象
from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger    # 分頁使用的類和異常處理的包
from django.contrib import auth      # 登錄,退出,驗證使用的包
from django.contrib.auth.decorators import login_required       # 防止未登錄就直接訪問後臺頁面使用的包
from django.contrib.auth.models import User        # 引入用戶表
from django.contrib.auth.hashers import make_password    # 密碼加密使用的包
import os
import uuid   # 生成唯一標識符


# 顯示數據庫內容業務邏輯函數
@login_required       # 防止未登錄而直接訪問後臺頁面
def manage(request):
    stus = models.Student.objects.all()   # 獲取數據庫所有行的數據
    #  根據搜索框的name獲取到,
    search = request.GET.get('search', None)   # 獲取搜索框的name
    order = request.GET.get('order', None)  # 通過什麼字段來排序
    rule = request.GET.get('rule', None)   # 排序方式
    pn = request.GET.get('pn',1)  # 分頁使用變量



   # GET方式獲取,來處理搜索功能
   try:


        if search is not None:
            # 一個Q就是一個條件,然後用並集操作符連接
            condition = Q(name__icontains=search) | Q(score__icontains=search) | Q(age__icontains=search) | Q(
                email__icontains=search) | Q(cls__name__icontains=search)
            stus = models.Student.objects.filter(condition)
    else:  # 沒有搜索條件就默認顯示所有
             stus = models.Student.objects.all()


   except Exception as e:

          print e



   # 排序規則的業務邏輯部分

   if order:
          if rule == 'u':   # 升序排序
              stus = stus.order_by(order)
          else:      # 降序排序
              stus = stus.order_by(order).reverse()

   

   # 分頁規則的業務邏輯部分

   # 分頁返回的值是unicode轉成int
    try:
        pn = int(pn)
    except Exception as e:
        pn = 1


    # 從客戶端瀏覽器中讀取每頁顯示記錄條數的cookie值,如果沒有輸入則默認爲5
    per_page = request.COOKIES.get('per_page',5)


    # 分頁功能處理
    try:
        paginator = Paginator(stus,per_page)    # 返回一個分頁對象,p1:queryset,p2:每頁記錄條數
        stus = paginator.page(pn)  # 獲取某一頁的記錄
    except(InvalidPage,EmptyPage,PageNotAnInteger) as e:
        pn = 1
        stus = paginator.page(pn)  # 獲取某一頁的記錄
        print e


    num_pages = stus.paginator.num_pages    # 獲取總頁數


    if num_pages<5:         # 如果最大頁數小於你想要顯示的數字
        start = 1
        end = num_pages+1

    else:
        if pn <= 2:  # 頁數左邊界
            start = 1
            end = 6
        elif pn>=num_pages-2:  # 頁數右邊界
            start = num_pages-4
            end = num_pages + 1
        else:      # 頁數不觸及邊界的情況
            start = pn-2
            end = pn+3
    # 分頁數字生成
    page_nums = range(start,end)


    # 返回響應
    return render(request,'pro01/manage.html',{'stus':stus,'index':'active','page_nums':page_nums})


注意:以上內容是個人使用的隨手記錄, 就是介紹了下簡單的使用

歡迎大家來吐槽,準備好瓜子飲料礦泉水,開整!!!

---------------------------------------------------------------------------------------

搞笑:能動手就儘量別吵吵


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