在写django项目的时候,有的数据没有使用模型管理(数据表是动态添加的),所以要直接使用mysql。前端请求数据的时候可能会指定这几个参数:要请求的页号,页大小,以及检索条件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
"""
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@login_required
def 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!--列表分页器-->
< div class = "pagination" >
< span class = "step-links" >
{% if events.has_previous %}
< a href = "?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 = "?page={{ events.next_page_number }}&name={{ name }}" rel = "external nofollow" >next</ a >
{% endif %}
</ span >
</ div >
{% include 'include/pager.html' %}
|
以上这篇利用python对mysql表做全局模糊搜索并分页实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Monster_ixx/article/details/105056756