Django 序列化三种方式 对象 列表 元组

1.xuliehua.html

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<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',
success:function (arg) {
//$('#tb').append(arg);
if(arg.status){
console.log(arg.data);
//var v = JSON.parse(arg.data); }
}
})
}
</script>
</body>
</html>

2.views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse
from app01 import models
import json
def xuliehua(request): return render(request,'xuliehua.html') """
def get_data(request):
user_list = models.UserInfo.objects.all()
return render(request,'get_data.html',{'user_list':user_list})
"""
def get_data(request):
from django.core import serializers ret = {'status':True,'data':None}
try:
     # 1.序列化对象QuerySet
# user_list = models.UserInfo.objects.all()
# QuerySet【obj,obj,obj】
# ret['data'] = serializers.serialize("json",user_list)
#
# //前端 ajax序列化
# var v = JSON.parse(arg.data);      # 2.序列化元组
# user_list = models.UserInfo.objects.all().values('id','username')
# ret['data'] = list(user_list)
# //前端 ajax直接取值
# var v = arg.data;

# 3.序列化列表
# user_list = models.UserInfo.objects.all().values_list('id', 'username')
# ret['data'] = list(user_list)
# //前端 ajax直接取值
# var v = arg.data;
pass
except Exception as e:
ret['status'] = False
result = json.dumps(ret)
return HttpResponse(result)
上一篇:IO调度 | Linux块设备中的IO路径及调度策略


下一篇:nginx代理图片访问