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())
合集:
python_django
分类:
编程相关 / Python
, 编程相关
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了