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())
标签:username,__,mobile,查询,person,django,动态,page
From: https://www.cnblogs.com/HeroZhang/p/18066002