利用python对mysql表做全局模糊搜索并分页实例
在写django项目的时候,有的数据没有使用模型管理(数据表是动态添加的),所以要直接使用mysql。前端请求数据的时候可能会指定这几个参数:要请求的页号,页大小,以及检索条件。
"""
tableName:表名
pageNum:请求的页的编号
pageSize:每一页的大小
searchInfo:需要全局查询的信息
"""
defgetMysqlData(tableName,pageNum,pageSize,searchInfo):
#使用MySQLdb获取的mysql游标
cursor=getCursor()
#用以获取列标题
colSql='select*from{}limit1'.format(tableName)
cursor.execute(colSql)
columns=[col[0]forcolincursor.description]
#转化查询信息为sql
searchCondition=','.join(columns)
searchInfo="WHERECONCAT({})like'%{}%'".format(searchCondition,searchInfo)
#用以获取总数
totalSql="selectcount(*)from{}{};".format(tableName,searchInfo)
cursor.execute(totalSql)
total=cursor.fetchone()[0]
#用以获取具体数据
limit1=(pageNum-1)*pageSize
limit2=pageSize
dataSql="select*from{}{}limit{},{};".format(tableName,searchInfo,limit1,limit2)
cursor.execute(dataSql)
data=[
dict(zip(columns,row))
forrowincursor.fetchall()
]
return(total,columns,data)
"""
total:符合条件的数据总数
columns:字段名列表
['字段名1','字段名2',...]
data:数据对象列表
[{'字段名1':数据1,'字段名2':数据1,...},{'字段名1':数据2,'字段名2':数据2,...},...]
"""
补充知识:django分页查询搜索--传递查询参数,翻页时带上查询参数
django在分页查询的时候,翻页时,v层要传递查询参数,相应的html翻页连接也要带上查询参数
直接上代码
view:
@login_required
defsearch_name(request):
username=request.session.get('user')
search_name=request.GET.get('name')
ifsearch_name==None:
search_name=request.GET.get('name')
event_list=Event.objects.filter(name__contains=search_name)
paginator=Paginator(event_list,2)
page=request.GET.get('page')
try:
contacts=paginator.page(page)
exceptPageNotAnInteger:
#如果page不是整数,取第一页面数据
contacts=paginator.page(1)
exceptEmptyPage:
#如果page不在范围内,则返回最后一页数据
contacts=paginator.page(paginator.num_pages)
returnrender(request,'event_manage.html',{'user':username,'events':contacts,'name':search_name})
html:
{%ifevents.has_previous%} previous {%endif%} Page{{events.number}}of{{events.paginator.num_pages}} {%ifevents.has_next%} next {%endif%}
以上这篇利用python对mysql表做全局模糊搜索并分页实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。