Django1.11 的serializers序列化model

开发环境:Django1.11  Python3

如果想把很多model转化成json格式可以直接这样写:

from django.views.generic.base import View
from django.http import HttpResponse
from django.core import serializers

from goods.models import Goods


class GoodsListView(View):

    def get(self, request):
        # 取前十个good的model
        goods = Goods.objects.all()[:10]
        # 利用serializers的serialize直接把所有model转化成json格式
        json_data = serializers.serialize('json', goods)  
        # 必须要标明返回的 content_type 是 application/json
        return HttpResponse(json_data, content_type='application/json')

 

当然你也可以用Django的 JsonResponse,直接返回Ptyhon字典、列表等(可以dump成json格式)的type

from django.views.generic.base import View
from django.http import JsonResponse
from django.forms.models import model_to_dict

from goods.models import Goods

class GoodsListView(View):

    def get(self, request):
        json_list = []
        for good in goods:
            json_data = model_to_dict(good)
            json_list.append(json_data)
        # 这里要把safe设置成False,否则会Django报错,可以点进去看JsonResponse源码
        return JsonResponse(json_list, safe=False)    

 

posted @ 2017-09-26 20:13  WangC.W  阅读(368)  评论(0编辑  收藏  举报