python django 資料JSON序列化

2021-09-24 16:56:28 字數 999 閱讀 6877

最近初入大神級語言。。。 python....準備做個小系統 初試牛刀

被 django框架各種方便征服...(直接拿來可用)

好了,說正題: 

在使用layui做**分頁的時候遇到需要將 後台django objects filter的資料 轉換成json 的問題(如需看正確**,請直接拖到最後,老同志愛吐槽)

import json

user_list=models.user.objects.filter(createtime__gt=searchdatestart)

return render(request,"user_list.html",json.dumps(user_list))

天真的直接使用了  python 自帶的json 序列化工具,於是報了如下錯誤

object of type queryset is not json serializable

參考了這段解決思路後,在filter之後直接用value 限定輸出內容,結果錯誤變成了

typeerror: datetime is not json serializable

最後使用了 django的 djangojsonencoder 才順利搞定

正確**如下:

import json

user_list=models.user.objects.filter(createtime__gt=searchdatestart).values('userid','createtime','lastlogintime')

return render(request,"user_list.html"

,json.dumps(list(user_list)

,sort_keys=true

,indent=1

,cls=djangojsonencoder))

python django 資料庫查詢

exact 精確等於 like aaa iexact 精確等於 忽略大小寫 ilike aaa contains 包含 like aaa icontains 包含 忽略大小寫 ilike aaa 但是對於sqlite來說,contains的作用效果等同於icontains。gt 大於 gte 大於等...

python django 資料庫查詢

exact 精確等於 like aaa iexact 精確等於 忽略大小寫 ilike aaa contains 包含 like aaa icontains 包含 忽略大小寫 ilike aaa 但是對於sqlite來說,contains的作用效果等同於icontains。gt 大於 gte 大於等...

python django 資料查詢條件

查詢使用者的狀態是2或者是4的情況 空值和空字串是不一樣的東西!需要注意的是 專案setting.py裡面的時區採用的是美國的時區,我們不要使用這個時區 使用這個時區的,我們輸入的日期會進行轉換,最終不一樣 將use tz flase 指定時間之前,或者之後 外來鍵查詢 python 3.7.6 d...