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

it2022-05-07  1

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)

 

转载于:https://www.cnblogs.com/icemonkey/p/10540005.html


最新回复(0)