数据查询分页功能和排序功能大家都很熟悉,本文以一个小例子介绍一下Django后台实现
数据列表
id依次从6到1
[
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:36",
"ModifyTime": "2016-05-22 00:06:36",
"IsDelete": "False",
"Type": "test",
"id": "6",
"idUser_id": "1"
},
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:17",
"ModifyTime": "2016-05-22 00:06:17",
"IsDelete": "False",
"Type": "test",
"id": "5",
"idUser_id": "1"
},
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:17",
"ModifyTime": "2016-05-22 00:06:17",
"IsDelete": "False",
"Type": "test",
"id": "4",
"idUser_id": "1"
},
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:16",
"ModifyTime": "2016-05-22 00:06:16",
"IsDelete": "False",
"Type": "test",
"id": "3",
"idUser_id": "1"
},
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:15",
"ModifyTime": "2016-05-22 00:06:15",
"IsDelete": "False",
"Type": "test",
"id": "2",
"idUser_id": "1"
},
{
"detail": "this is test",
"CreateTime": "2016-05-22 00:06:12",
"ModifyTime": "2016-05-22 00:06:12",
"IsDelete": "False",
"Type": "test",
"id": "1",
"idUser_id": "1"
}
]
分页显示
分页有两个重要的参数,一个是每页显示的记录条数,一个是页码。
数据表查询主体代码,实现比较简单,就不解释太多,直接看代码
稍微提醒下的两点,网上很多文章都介绍了
1、分片代码lUserLogs[start:end],这样书写只会从数据库中获取onePageCount数据,不会获取所有数据
2、lUserLogs.count()方式统计总数,不要用len(lUserLogs),前者是select count(*)语法,后者会返回整个查询结果集
分页获取第一页
onePageCount表示单页个数,默认为20,page表示页码,默认为1
GET http://127.0.0.1:8000/UserLog/?onePageCount=2&page=1
-- response --
200 OK
Date: Sun, 22 May 2016 04:07:04 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Set-Cookie: csrftoken=MA0QfFh87zllpjQT0BLuPB16F7WAOiH8; expires=Sun, 21-May-2017 04:07:04 GMT; Max-Age=31449600; Path=/
[{"detail": "this is test", "CreateTime": "2016-05-22 00:06:36", "ModifyTime": "2016-05-22 00:06:36", "IsDelete": "False", "Type": "test", "id": "6", "idUser_id": "1"}, {"detail": "this is test", "CreateTime": "2016-05-22 00:06:17", "ModifyTime": "2016-05-22 00:06:17", "IsDelete": "False", "Type": "test", "id": "5", "idUser_id": "1"}]
分页获取第二页
GET http://127.0.0.1:8000/UserLog/?onePageCount=2&page=2
-- response --
200 OK
Date: Sun, 22 May 2016 04:11:07 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Set-Cookie: csrftoken=MA0QfFh87zllpjQT0BLuPB16F7WAOiH8; expires=Sun, 21-May-2017 04:11:07 GMT; Max-Age=31449600; Path=/
[{"detail": "this is test", "CreateTime": "2016-05-22 00:06:17", "ModifyTime": "2016-05-22 00:06:17", "IsDelete": "False", "Type": "test", "id": "4", "idUser_id": "1"}, {"detail": "this is test", "CreateTime": "2016-05-22 00:06:16", "ModifyTime": "2016-05-22 00:06:16", "IsDelete": "False", "Type": "test", "id": "3", "idUser_id": "1"}]
排序
我这的数据表很多都需要排序,默认的排序方式都一样,所以提取出基类如下
排序代码ordering = [‘-ModifyTime‘,‘-CreateTime‘,‘-id‘]
-符号表示逆序,从大到小,从最新的到最老的
实际的表继承基类即可
返回的数据就如同文首的数据以及本文其他的JSON返回数据结构一样,按照ordering定义的顺序排列