數據查詢分頁功能和排序功能大家都很熟悉,本文以一個小例子介紹一下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定義的順序排列



