【服务后端】Django 返回的QuerySet序列化
QuerySet序列化一般可以先写一个公共的常用的解析函数,参考前面的博文《【服务后端】Python序列化对象为Json方法》
http://www.cnblogs.com/inns/p/5507012.html
所有字段按照其类型来解析,外键返回id即可
后面介绍一些特殊序列化需求及实现
1、三个关联表
User和Class表,以及ClassUserTemp表,
1.1 User表
2.2 Class表
3.3 ClassUserTemp表
2、 ClassUserTemp查询
经常会出现查询ClassUserTemp表的场景
例如pUserClasses = ClassUserTemp.objects.filter(idClass__Owner=lUser).values("idClass","idUser")
返回给APP的Json数据需要序列化,我们一般都会建立一个公共的序列化函数,ClassUserTemp序列化之后返回给APP的就是Class和User的Id。
return JsonResponse(pUserClasses )
但有时候需要定制化返回给APP一些信息,例如把User和Class的名称也带上
2.1 序列化之后赋值(效率低)
pUserClasses = ClassUserTemp.objects.filter(idClass__Owner=lUser)
pUserClassesJson = pUserClasses.values("idClass","idUser")
for pUserClasseJson in pUserClassesJson:
pUserClasseJson["idClass_Name"] = pUserClasses.filter(idClass__id=pUserClasseJson["idClass"])[0].idClass.ClassName
pUserClasseJson["idUser_Name"] = pUserClasses.filter(idUser__id=pUserClasseJson["idUser"])[0].idUser.UserName
return JsonResponse(pUserClasseJson)
2.2 从QuerySet序列化(比上一方法效率高)
pUserClasses = ClassUserTemp.objects.filter(idClass__Owner=lUser)
pUserClassesJson = []
for pUserClass in pUserClasses:
pUserClassesJson.append({
"idClass":pUserClass.idClass.id,
"idClass_Name":pUserClass.idClass.ClassName,
"idUser":pUserClass.idUser.id,
"idUser_Name":pUserClass.idUser.UserName
})
return JsonResponse(pUserClasseJson)
3 查询返回结果
GET http://127.0.0.1:8000/JoinClass/?OwnerFlag=my
-- response --
200 OK
Date: Fri, 20 May 2016 03:20:02 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Set-Cookie: csrftoken=MA0QfFh87zllpjQT0BLuPB16F7WAOiH8; expires=Fri, 19-May-2017 03:20:02 GMT; Max-Age=31449600; Path=/
[{"idUser": "2", "idClass": "5", "idClass_Name": "123", "idUser_Name": "in"}, {"idUser": "2", "idClass": "6", "idClass_Name": "\u4e00\u5e74\u7ea7\u4e00\u73ed", "idUser_Name": "in"}]