django序列化的几种方法
Posted chvv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django序列化的几种方法相关的知识,希望对你有一定的参考价值。
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序列化的几种方法的主要内容,如果未能解决你的问题,请参考以下文章