利用python對mysql表做全局模糊搜索并分頁實例
在寫django項目的時候,有的數據沒有使用模型管理(數據表是動態添加的),所以要直接使用mysql。前端請求數據的時候可能會指定這幾個參數:要請求的頁號,頁大小,以及檢索條件。
'''tableName: 表名pageNum: 請求的頁的編號pageSize: 每一頁的大小searchInfo: 需要全局查詢的信息'''def getMysqlData(tableName, pageNum, pageSize, searchInfo):# 使用MySQLdb獲取的mysql游標 cursor = getCursor() # 用以獲取列標題 colSql = ’select * from {} limit 1’.format(tableName) cursor.execute(colSql) columns = [col[0] for col in cursor.description] # 轉化查詢信息為sql searchCondition = ’,’.join(columns) searchInfo = 'WHERE CONCAT({}) like ’%{}%’'.format(searchCondition, searchInfo) # 用以獲取總數 totalSql = 'select count(*) 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)) for row in cursor.fetchall() ] return (total, columns, data)'''total: 符合條件的數據總數columns: 字段名列表 [’字段名1’, ’字段名2’, ...]data: 數據對象列表 [{’字段名1’: 數據1,’字段名2’:數據1, ...},{’字段名1’: 數據2, ’字段名2’: 數據2, ...}, ...]'''
補充知識:django 分頁查詢搜索--傳遞查詢參數,翻頁時帶上查詢參數
django在分頁查詢的時候,翻頁時,v層要傳遞查詢參數,相應的html翻頁連接也要帶上查詢參數
直接上代碼
view:
@login_requireddef search_name(request): username = request.session.get(’user’) search_name = request.GET.get(’name’) if search_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) except PageNotAnInteger: # 如果page不是整數,取第一頁面數據 contacts = paginator.page(1) except EmptyPage: # 如果page不在范圍內,則返回最后一頁數據 contacts = paginator.page(paginator.num_pages) return render(request,’event_manage.html’,{’user’:username,’events’:contacts,’name’:search_name})
html:
<!--列表分頁器--> <div class='pagination'> <span class='step-links'> {% if events.has_previous %} <a href='http://www.cgvv.com.cn/bcjs/?page={{ events.previous_page_number }}&&name={{ name }}' rel='external nofollow' >previous</a> {% endif %} <span class='current'> Page {{ events.number }} of {{ events.paginator.num_pages }} </span> {% if events.has_next %} <a href='http://www.cgvv.com.cn/bcjs/?page={{ events.next_page_number }}&name={{ name }}' rel='external nofollow' >next</a> {% endif %} </span> </div> {% include ’include/pager.html’ %}
以上這篇利用python對mysql表做全局模糊搜索并分頁實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: