序列化
1.Django ajax 为甚么要用序列化 因为django ajax 收发数据只能一字符串的形式 2.为什么python json不能序列化Jquery对象 python json 只能识别 python的类型,所以只能序列化 str list dict... 3.在django 中专门用来序列化的方法
1.对象序列化(类型 QuerySet[obj,])
query_obj = models.UserInfo.objects.all()
ret['data'] = serializers.serialize("json",query_obj)
ret1= json.dumps(ret)
注释:a. 先把ret[ret['data']的值用json序列化 b. 最终把整个返回的字典序列化
2.字典序列化
#例如
#<QuerySet [{'username': '邹兆外', 'id': 2}, {'username': '杨建', 'id': 3}, {'username': '小云云', 'id': 4}, {'username': '大模', 'id': 5}]>
user_list = models.UserInfo.objects.all().values('id','username')
ret['data'] = list(user_list)
ret1= json.dumps(ret)
注释:a. 先把<QuerySet> ret['data'] 转换成list
b. json序列化列表
3.列表学序列化
#例如<QuerySet [(2, '邹兆外'), (3, '杨建'), (4, '小云云'), (5, '大模')]>
user_list = models.UserInfo.objects.all().values_list('id', 'username')
ret['data'] = list(user_list)
ret1= json.dumps(ret)
关于Django中的序列化主要应用在将数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为Json格式。
知识点扩充
1、serializers
from django.core import serializers
ret = models.BookType.objects.all()
data = serializers.serialize("json", ret)
2.json.dumps
import json
#ret = models.BookType.objects.all().values('caption')
ret = models.BookType.objects.all().values_list('caption')
ret=list(ret)
result = json.dumps(ret)
由于json.dumps时无法处理datetime日期,所以可以通过自定义处理器来做扩展,如:
import json from datetime import date from datetime import datetime class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field, date): return o.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, field) # ds = json.dumps(d, cls=JsonCustomEncoder)
1.通过后台渲染数据 返回页面上
views 获得数据
from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def serialize(request): return render(request,'serialize.html') def get_data(request): user_list = models.UserInfo.objects.all() return render(request,'get_data.html',{'user_list':user_list})
serialize html 渲染数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>用户列表</p> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { initData(); }); function initData() { $.ajax( { url:'/get_data/', type:'GET', success:function (arg) { if (arg) { $('#tb').append(arg); } } } ) } </script> </body> </html>
get_data 得到数据
{% for row in user_list%} <tr> <td>{{row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.email }}</td> </tr> {% endfor %}
过程注释:
通过页面get_data return render() 渲染完毕,返回字符串数据 手动给serialize.html 表格添加
2.若表特别大,回特别耗时间,需要全部渲染完了,才能返回,效率过低。试图:不要反回整个页面,只要数据
试图用json序列化 到前段反序列化
会报错,因为对象是queryset对象,json不能序列该类型
解决方案:对象序列化(类型 QuerySet[obj,])
ret['data'] = serializers.serialize("json",query_obj)
ret1= json.dumps(ret)
serialize.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>用户列表</p> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { initData(); }); function initData() { $.ajax( { url:'/get_data/', type:'GET', dataType:'JSON', #反序列化ret 整体返回字符串 success:function (arg) { if (arg) { var a=JSON.parse(arg.data); #反序列话data $('#tb').append(arg) console.log(a) } } } ) } </script> </body> </html>
get_data 得到数据
{% for row in user_list%}
<tr>
<td>{{row.id }}</td>
<td>{{ row.username }}</td>
<td>{{ row.email }}</td>
</tr>
{% endfor %}
views 获得数据
from django.shortcuts import render,HttpResponse
import json
# Create your views here.
from app01 import models
def serialize(request):
return render(request,'serialize.html')
def get_data(request):
from django.core import serializers
ret={'status':True,'data':None}
try:
user_list = models.UserInfo.objects.all()
ret['data']=serializers.serialize('json',user_list)
except Exception as e:
ret['status']=False
result=json.dumps(ret)
return HttpResponse(result)
如果序列化字典
解决方案:对象序列化(类型 QuerySet[(),])
user_list = models.UserInfo.objects.all().values('id','username')
ret['data'] = list(user_list)
ret1= json.dumps(ret)
serialize.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>用户列表</p>
<table id="tb">
</table>
<script src="/static/jquery-3.1.1.js"></script>
<script>
$(function () {
initData();
});
function initData() {
$.ajax(
{
url:'/get_data/',
type:'GET',
dataType:'JSON', #反序列化ret 整体返回字符串
success:function (arg) {
if (arg) {
$('#tb').append(arg)
console.log(a)
}
}
}
)
}
</script>
</body>
</html>
get_data 得到数据
{% for row in user_list%} <tr> <td>{{row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.email }}</td> </tr> {% endfor %}
views 获得数据
from django.shortcuts import render,HttpResponse
import json
# Create your views here.
from app01 import models
def serialize(request):
return render(request,'serialize.html')
def get_data(request):
from django.core import serializers
ret={'status':True,'data':None}
try:
user_list = models.UserInfo.objects.all().values('id','username')
ret['data']=list[user_list] #转换成list
except Exception as e:
ret['status']=False
result=json.dumps(ret)
return HttpResponse(result)
列表学序列化
user_list = models.UserInfo.objects.all().values_list('id', 'username')
ret['data'] = list(user_list)
ret1= json.dumps(ret)
serialize.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>用户列表</p> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { initData(); }); function initData() { $.ajax( { url:'/get_data/', type:'GET', dataType:'JSON', #反序列化ret 整体返回字符串 success:function (arg) { if (arg) { $('#tb').append(arg) console.log(a) } } } ) } </script> </body> </html>
get_data 得到数据
{% for row in user_list%} <tr> <td>{{row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.email }}</td> </tr> {% endfor %}
views 获得数据
from django.shortcuts import render,HttpResponse
import json
# Create your views here.
from app01 import models
def serialize(request):
return render(request,'serialize.html')
def get_data(request):
from django.core import serializers
ret={'status':True,'data':None}
try:
user_list = models.UserInfo.objects.all().values_list('id','username')
ret['data']=list[user_list] #转换成list
except Exception as e:
ret['status']=False
result=json.dumps(ret)
return HttpResponse(result)