Django 内置序列化

serializers

   Django中提供了非常便捷的序列化组件,特别是对前后端分离项目来说使用非常的方便。

   如果我们想对QuerySet进行序列化,那么使用这个是非常棒的选择!

from django.core import serializers
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.core import serializers
from app01 import models

def test(request):
    if request.method == "POST":
        user_queryset = models.UserTest.objects.all()
        res = serializers.serialize("json",user_queryset) # 序列化类型,序列化内容
        return HttpResponse(res)

    return render(request,"base.html",locals())

  

<body>
    <button type="button">获取数据</button>
</body>
<script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js'></script>
<script>
    window.onload = (() => {
        document.querySelector("button").addEventListener("click", (ele) => {
            $.ajax({
                url: "http://127.0.0.1:8000/",
                type: "post",
                dataType: 'JSON',
                success: (res) => {
                    console.log(res);
                },
                error:()=>{
                    console.log("失败");
                }
            })

        })
    })
</script>

   格式化出的数据:

[{
	"model": "app01.usertest",
	"pk": 1,
	"fields": {
		"name": "Yunya",
		"age": 18,
		"gender": false
	}
}, {
	"model": "app01.usertest",
	"pk": 2,
	"fields": {
		"name": "Jack",
		"age": 19,
		"gender": true
	}
}, {
	"model": "app01.usertest",
	"pk": 3,
	"fields": {
		"name": "Tom",
		"age": 18,
		"gender": false
	}
}, {
	"model": "app01.usertest",
	"pk": 4,
	"fields": {
		"name": "Marin",
		"age": 16,
		"gender": true
	}
}]
posted @ 2020-10-22 19:38  云崖先生  阅读(93)  评论(0编辑  收藏  举报