• 【django】序列化


    1.对象

    对于Django的Queryset<Queryset [object,object,object]>这种关于django的Querysetset对象这种是不能用python的json方法,需要用到django的 serializers模块

    传递给 serialize 方法的参数有二点:

    a.个序列化目标格式,

    b.一个是序列号的对象QuerySet. (事实上,第二个参数可以是任何可迭代的Django Model实例,但它很多情况下就是一个QuerySet).

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    from app02 import views as v2
    from app03 import views as v3
    
    urlpatterns = [
        url(r'^xuliehua/', v3.xuliehua),
        url(r'^get_data/', v3.get_data),
    ]
    project/urls.py
    <!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) {
                        //$('#tb').append(arg);
                        if (arg.status){
                            //console.log(arg.data);
                            var v = JSON.parse(arg.data);
                            console.log(v);
                        }
                    }
                })
    
            }
        </script>
        
    </body>
    </html>
    templates/xuliehua.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        {% for row in user_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.username }}</td>
                <td>{{ row.email }}</td>
            </tr>
        {% endfor %}
    
    </body>
    </html>
    templates/get_data.html
    from django.shortcuts import render,HttpResponse
    from app01 import models
    import json
    
    def xuliehua(request):
        return render(request,'xuliehua.html')
    
    def get_data(request):
        from django.core import serializers
        ret ={'status':True,'data':None}
        try:
            # 1.对象转字符串(序列化)
            user_list = models.UserInfo.objects.all()
            # QuerySet【obj,obj,obj】
            ret['data'] = serializers.serialize("json",user_list)
            # 通过Django 内置序列化
    
        except Exception as e:
            ret['status'] = False
        result = json.dumps(ret)
        return HttpResponse(result)
    app003/views.py

    2.字典

    关于python一些内置一些类型(例如:字典,列表,元祖。。。)的序列化,就用json 就可以了

    <!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) {
                        //$('#tb').append(arg);
                        if (arg.status){
                            console.log(arg.data);
                            //var v = JSON.parse(arg.data);
                            //console.log(v);
                        }
                    }
                })
    
            }
        </script>
        
    </body>
    </html>
    templates/xuliehua.html
    from django.shortcuts import render,HttpResponse
    from app01 import models
    import json
    
    def xuliehua(request):
        return render(request,'xuliehua.html')
    
    def get_data(request):
        from django.core import serializers
        ret ={'status':True,'data':None}
        try:
            # 2.字典转字符串(序列化)
            user_list = models.UserInfo.objects.all().values('id','username')
            ret['data'] = list(user_list)
            # user_list最外面querySet,里面是字典;list(user_list)相当于把querySet list化
    
        except Exception as e:
            ret['status'] = False
        result = json.dumps(ret)
        return HttpResponse(result)
    app003/views.py

     

    3.元组

    <!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) {
                        //$('#tb').append(arg);
                        if (arg.status){
                            console.log(arg.data);
                            //var v = JSON.parse(arg.data);
                            //console.log(v);
                        }
                    }
                })
    
            }
        </script>
        
    </body>
    </html>
    templates/xuliehua.html
    from django.shortcuts import render,HttpResponse
    from app01 import models
    import json
    
    def xuliehua(request):
        return render(request,'xuliehua.html')
    
    def get_data(request):
        from django.core import serializers
        ret ={'status':True,'data':None}
        try:
            # 3.元组转字符串(序列化)
             user_list = models.UserInfo.objects.all().values_list('id', 'username')
             ret['data'] = list(user_list)
            # user_list最外面querySet,里面是元组;list(user_list)相当于把querySet list化
    
        except Exception as e:
            ret['status'] = False
        result = json.dumps(ret)
        return HttpResponse(result)
    app003/views.py

     

  • 相关阅读:
    NGUI Sprite 和 Label 改变Layer 或父物体后 未更新深度问题
    unity销毁层级物体及 NGUI 深度理解总结
    unity 2d 和 NGUI layer
    关于NGUI与原生2D混用相互遮盖的问题心得
    CentOS7为firewalld添加开放端口及相关操作
    Python 操作redis有序集合(sorted set)
    win10下安装redis 服务
    python2/3中 将base64数据写成图片,并将图片数据转为16进制数据的方法、bytes/string的区别
    解决最小化安装Centos7后无法上网的问题,以及安装成功后的基本配置
    在mysql中使用group by和order by取每个分组中日期最大一行数据,亲测有效
  • 原文地址:https://www.cnblogs.com/dalyday/p/9136763.html
Copyright © 2020-2023  润新知