原文地址:https://www.cnblogs.com/ziyoublog/p/9001517.html。
前后端数据传输的两种方式: httpresponse 需要json.dumps,还需要拼接成字符串
jsonresponse 不需要json.dumps 序列化,传输的直接是字符串
json序列化的方式:
1. 简单序列化(ajax请求时,后端直接返回数据)
import json
result = {"password": password, "encrypt": encrypt_str}
return HttpResponse(json.dumps(result), content_type="application/json")
2. 简单的序列化:
def query(request):
users = User.objects.all().values() #返回字典形式的QuerySet
json_str = json.dumps(list(users)) #将QuerySet对象转为list
return HttpResponse(json_str)
3. 简单的序列化:
def mydefault(u):
if isinstance(u,User):
return {"name":u.name,'age':u.age,'salary':u.salary,'birthday':u.birthday.strftime('%Y-%m-%d')}
users = list(User.objects.all()) # 查询mysql数据库中的user->QuerySet,并转为list
user_dump = json.dumps(users,default=mydefault)
4. 简单的序列化:
def query1(request):
user = User.objects.get(pk=1)
def user_default(u):
if isinstance(u,User):
return {"name":u.name,'age':u.age,'salary':u.salary,'birthday':u.birthday.strftime('%Y-%m-%d')}
return JsonResponse(user,safe=False,json_dumps_params={"default":user_default})
def query2(request):
users = list(User.objects.all())
def user_default(u):
if isinstance(u,User):
return {"name":u.name,'age':u.age,'salary':u.salary,'birthday':u.birthday.strftime('%Y-%m-%d')}
return JsonResponse({"users":users},json_dumps_params={"default":user_default})
5. django提供的序列化
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.core import serializers
user_obj = User.objects.filter(pk=id)
json_data = serializers.serialize('json', user_obj)
json_data = json.loads(json_data)
return JsonResponse(json_data, safe=False)
6. geojson的django自带方法序列化(这个要安装geodjango)
from django.core.serializers import serialize
def distribution_geojson_by_name(request):
name = request.GET.get('name', '')
if len(name) != 0:
query_set = Specimen.objects.filter(chinesename=name)
geojson = serialize('geojson', query_set,
geometry_field='geom',
fields=('verbatimlocality',))
return HttpResponse(geojson, content_type="application/json")
7.复杂的设计到分页的json序列化
from django.core.paginator import Paginator
def Article(request):
page_num = request.GET.get('page')
row_num = request.GET.get('rows')
print(page_num, row_num)
rows = []
chapter = Chapter.objects.all()
all_page = Paginator(chapter, row_num)
page = Paginator(chapter, row_num).page(page_num).object_list
page_data = {
"total": all_page.num_pages,
"records": all_page.count,
"page": page_num,
"rows": rows
}
for i in page:
rows.append(i)
def myDefault(u):
if isinstance(u, Chapter):
return {'id': u.id,
'title': u.name,
'size': u.size,
'duration': u.duration,
'download_url': "不能下载",
"audiopath": str(u.audiopath)
}
data = json.dumps(page_data, default=myDefault)
return HttpResponse(data)
8. Redis 的序列化
import json
from redis import Redis
from datetime import datetime
red = Redis(host='192.168.134.154',port=8000) # 连接redis数据库
def mydefault(u):
if isinstance(u,User):
return {"name":u.name,'age':u.age,'salary':u.salary,'birthday':u.birthday.strftime('%Y-%m-%d')}
users = list(User.objects.all()) # 查询mysql数据库中的user->QuerySet,并转为list
user_dump = json.dumps(users,default=mydefault) # 将model数据 转为 json字符串
print(user_dump)
red.set('userlist',user_dump) # 将json字符串以key-value的形式存储到redis中
反序列化
反序列化过程:获取redis数据库中的数据get -> json字符串 -> 提取字符串中的数据(反序列化) -> Model对象
def parsedefault(dic): # u为list中的一个个dict
# dic['birthday'] = datetime.strptime(dic['birthday'],'%Y-%m-%d')
# dic['salary'] = Decimal(dic['salary'])
return User(name=dic['name'],age=dic['age'],salary=dic['salary'],birthday=dic['birthday'])
return User(**dic) 也直接可以用这个
res = red.get("userlist") # 返回bytes 需转为str b"xxx".decode("utf-8") -> str
results = json.loads(res.decode("utf-8"),object_hook=parsedefault)
只是从redis数据库中读出来的才需要decode(),其他的不需要decode
没有object_hook=parsedefault 也不会报错,只不过是得到的是字典,我们要转换成列表
print(results) #得到的是list类型,里面包含的是一个个model对象
- 多个json串的拼接
def get(self, request, *args, **kwargs):
page_num = request.GET.get('page')
row_num = request.GET.get('rows')
print(page_num, row_num)
parent_id = request.GET.get("parent_id")
# 专辑数据
album = Special_issue.objects.all().order_by('id')
chapter = Chapter.objects.all().filter(reserved_field01=parent_id)
data = {
"page": page_num,
"album": list(album),
"chapter": list(chapter),
}
def myDefault(u):
if isinstance(u, Chapter):
return {'id': u.id,
'title': u.name,
'size': u.size,
'duration': u.duration,
'download_url': "不能下载",
"audiopath": str(u.audiopath)
}
elif isinstance(u, Special_issue):
return {'id': u.id,
'title': u.name,
"creatime": u.chapter_count,
"description": u.describe,
}
data = json.dumps(data, default=myDefault)
return HttpResponse(data)
///////////// 运行结果
{
"page": "1",
"album": [
{
"id": 1,
"title": "兰花草",
"creatime": "50",
"description": "分布范围广"
},
{
"id": 2,
"title": "慧",
"creatime": null,
"description": "身体健康,万事如意"
}
],
"chapter": [
{
"id": 2,
"title": "吉祥如意",
"size": "3.00M",
"duration": "50",
"download_url": "不能下载",
"audiopath": "aud/1555750636203_撕夜.mp3"
}
]
}