django 动态查询实现过程

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())
posted @   冀未然  阅读(54)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示