序列化操作
- Errordict
- 自定义Encoder
- django的模块可以直接序列化
第一种:
from django.core import serializers # 通过这个模块对queryset对象可以直接序列化
ret = models.tb.objects.all()
data = serializers.serialize("json",ret) #这里指定将ret序列化为json
第二种:
ret = models.tb.objects.values('id','name')
v = list(ret)
json.dumps(v)
这样不可以对时间序列化,如果要序列化时间,序号使用json.dumps(v,cls=JsonCustomEncoder(说明这个需要自定制))

实例:通过ajax提交前端表单数据到后台,后台通过form表单进行验证,如果有错误,通过重写类进行一次json序列化返回给前台

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form id="loginform">
    {% csrf_token %}
    <input type="text" name="username" />
    <input type="password" name="pwd" />
    <a id="sub">提交</a>
</form>
<script src="/static/jquery-1.12.4.min.js"></script>
<script>
    $(function () {
        $('#sub').click(function () {
            $.ajax({
                url:'/app04/login',
                type:'POST',
                data:$('#loginform').serialize(),
                success:function (data) {
                    console.log(data);
                    arg = JSON.parse(data)
                },
                error:function () {
                    console.log(data)
                }
            })
        })
        }
            )
</script>
</body>
</html>
View Code

相关文章: