首页 > 代码库 > Django7 序列化

Django7 序列化

序列化

关于Django中的序列化主要应用在数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为JSON格式

Django序列化的三种方式

serializers

这是django内建的序列器,它可以很好的序列化QuerySet,但当他遇到单独的django model object时就会报错,并且它序列化出的model中如果包含DateTimeField时,输出数据中的时间是个datetime对象,无法直接当作序列化数据使用

from django.core import serializers
 
ret = models.BookType.objects.all()
data = serializers.serialize("json", ret)

json.dumps

import json
 
# ret = models.BookType.objects.all().values("caption")
ret = models.BookType.objects.all().values_list("caption")
 
ret = list(ret)
 
result = json.dumps(ret)

由于json.dumps时无法处理detetime日期,所以可以通过自定义处理器来做扩展

import json 
from datetime import date 
from datetime import datetime 
    
class JsonCustomEncoder(json.JSONEncoder): 
     
    def default(self, field): 
      
        if isinstance(field, datetime): 
            return o.strftime(%Y-%m-%d %H:%M:%S) 
        elif isinstance(field, date): 
            return o.strftime(%Y-%m-%d) 
        else: 
            return json.JSONEncoder.default(self, field) 
    
    
# ds = json.dumps(d, cls=JsonCustomEncoder)

序列化错误信息

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# Author: JiaChen
 
from django.shortcuts import render, HttpResponse, redirect
from django import forms
from django.forms import widgets
from django.forms import fields
import json
 
 
class LoginForm(forms.Form):
    username = fields.CharField()
    password = fields.CharField(
        max_length=64,
        min_length=12
    )
 
from django.core.exceptions import ValidationError
 
 
class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field, ValidationError):
            return {"code": field.code, "messages": field.messages}
        else:
            return json.JSONEncoder.default(self, field)
 
 
def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    elif request.method == "POST":
        ret = {"status": True, "error": None, "data": None}
        obj = LoginForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            ret["error"] = obj.errors.as_data()
        result = json.dumps(ret, cls=JsonCustomEncoder)
        return HttpResponse(result)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form id="fm">
        {% csrf_token %}
        <p><input type="text" name="username"></p>
        <p><input type="password" name="password"></p>
        <a id="submit">提交</a>
    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $("#submit").click(function () {
                $.ajax({
                    url: "/login.html",
                    type: "POST",
                    data: $("#fm").serialize(),
                    success: function (arg) {
                        console.log(arg);
                        arg = JSON.parse(arg);
                    },
                    error: function () {
 
                    }
                })
            });
        });
    </script>
</body>
</html>

Django7 序列化