码迷,mamicode.com
首页 > 其他好文 > 详细

django序列化的几种方法

时间:2018-09-12 01:27:35      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:value   get   core   objects   view   inview   list   序列   values   

class LoginView(View):
def get(self,request):
出错
publish_list = Publisher.objects.all()
return HttpResponse(json.dumps(publish_list))#无法打印,返回值是一个querset对象
#c出错
publish_list = list(Publisher.objects.all())
return HttpResponse(json.dumps(publish_list)) # 无法打印,返回值是一个querset对象
第一种打印全部
publish_list = list(Publisher.objects.all().values())
return HttpResponse(json.dumps(publish_list))
第二种打印指定的name和email
publish_list = list(Publisher.objects.all().values("name","email"))
return HttpResponse(json.dumps(publish_list))
第三种
publish_list = Publisher.objects.all()
temp = []
for publish in publish_list:
temp.append({
"name":publish.name,
"email":publish.email}
)
return HttpResponse(json.dumps(temp))
第四种
from django.forms.models import model_to_dict
publish_list = Publisher.objects.all()
temp = []
for publish in publish_list:
temp.append(model_to_dict(publish))
return HttpResponse(json.dumps(temp))
第五种
from django.core import serializers
publish_list = Publisher.objects.all()
ret = serializers.serialize("json",publish_list)
return HttpResponse(ret)

django序列化的几种方法

标签:value   get   core   objects   view   inview   list   序列   values   

原文地址:https://www.cnblogs.com/chvv/p/9631760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!