1. 程式人生 > >django序列化的幾種方法

django序列化的幾種方法

serial pre turn rom list request publish 一個 指定

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序列化的幾種方法