django 動態查詢實現過程

冀未然發表於2024-03-11

django 動態查詢實現過程

一、背景描述

在前端頁面上有查詢功能,要查詢的輸入選擇有username,address,mobile等,可以透過任意一個查詢,或者任意組合進行查詢。
後端,獲取傳入的數值。判斷哪個有輸入,再在資料庫中進行查詢

二、解決方案

根據條件,動態實現查詢過程

condition = {}
if username:
	condition['username__startWith'] = username
if address:
	condition['addr__contains'] = address
if mobile is not None:
	condition['mobile__endWith'] = mobile
person = User.objects.filter(**condition)

先查詢所有,或者固定篩選的條件,動態實現查詢過程

person = User.objects.all()
if username:
	person = person.filter(username__startWith= username)
if address:
	person = person.filter(addr__contains= address)
if mobile is not None:
	person = person.filter(mobile__endWith= mobile)

person = User.objects.filter(**condition)

三、後續操作

from django.core.paginator import Paginator

person = person.order_by('-create_tiem')  倒序

page = Paginator(person, page_size)
total_count = person.count()
total_page = page.num_pages
if page_num > total_page:
    page_num = 1
    
result = list(pag.page(page_num).object_list.values())

相關文章