目录
一、介绍
二、Django序列化的三种方式
三、序列化错误信息
一、介绍
关于Django中的序列化主要应用在数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为JSON格式
二、Django序列化的三种方式
1.serializers
from django.core import serializers ret = models.BookType.objects.all() data = serializers.serialize("json", ret)
2.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)
3.由于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)
三、序列化错误信息
account.py
#!/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)
login.html
<!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>
时间: 2024-10-05 10:16:33