序列化定义:
向后台发送请求数据,序列化返回一个数据,这个过程称之为序列化,或者也可以理解为,
把一个对象转换为字符串,这个转换完成以后的对象可以被保存到本地文件中,这个过程就称之为序列化。
反之:如果把一个字符串,或文件转换为一个对象,这个过程称之为反序列化。
示例一:(适用于数据量很少的场合)
# views from django.shortcuts import render, HttpResponse from day60app import models # Create your views here. def alignment(request): return render(request, "alignment.html") def get_data(request): user_list = models.UserTabel.objects.all() return render(request, "get_data.html", {"user_list": user_list}) # models from django.db import models # Create your models here. class UserTabel(models.Model): user = models.CharField(max_length=10) age = models.IntegerField email = models.EmailField(max_length=20) # 前端 页面一: <!DOCTYPE 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", success:function (arg) { {# console.log(arg)#} $("#tb").append(arg); } }) } </script> </body> </html> 页面二: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for row in user_list %} <tr> <td> {{ row.user }} </td> <td> {{ row.email }} </td> </tr> {% endfor %} </body> </html>
示例二:(serializers,django自带的序列化)
# views from django.shortcuts import render, HttpResponse from day60app import models from django.core import serializers import json def alignment(request): return render(request, "alignment.html") def get_data(request): ret = {"status": True, "data": None} try: # serializers,django自带的序列化,只能序列化QuerySet对象 # 基于对象的序列化 # user_list = models.UserTabel.objects.all() # ret["data"] = serializers.serialize("json", user_list) # 前端 # var v = JSON.parse(arg.data); # 基于字典的序列化,用list将QuerySet对象转换为list类型 # user_list = models.UserTabel.objects.all().values("id", "user") user_list = models.UserTabel.objects.all().values_list("id", "user") # 前端console.log(arg.data); ret["data"] = list(user_list) except Exception as e: ret["status"] = False result = json.dumps(ret) return HttpResponse(result) # 前端 <!DOCTYPE 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) { {# console.log(arg)#} if (arg.status){ console.log(arg.data); {# var v = JSON.parse(arg.data); /*基于serializers,django自带的序列化在进行反序列化*/#} } } }) } </script> </body> </html>