django中返回json操作
方式一、直接使用HttpResponse
和json
模块返回
1、导包
import json from django.http import HttpResponse from django.views.generic import View from goods import models
2、视图的返回
class GoodView(View): """ 定义一个产品的view """ def get(self, request, *args, **kwargs): json_list = [] goods = models.GoodsModel.objects.all()[:10] for good in goods: json_dict = {} json_dict['name'] = good.name json_dict['goods_num'] = good.goods_num # 返回一个dict-list(俗称对象数组) json_list.append(json_dict) return HttpResponse(json.dumps(json_list, ensure_ascii=False, indent=2), content_type='application/json')
方式二、使用model_to_dict
来返回
1、导包
import json from django.http import HttpResponse from django.views.generic import View from django.forms.models import model_to_dict from goods import models
2、视图类中书写
class GoodView1(View): """ 定义一个产品分类视图 """ def get(self, request, *args, **kwargs): json_list = [] goods = models.GoodsCategoryModel.objects.all()[:10] for good in goods: json_dict = model_to_dict(good) # 返回一个dict-list(俗称对象数组) json_list.append(json_dict) return HttpResponse(json.dumps(json_list, ensure_ascii=False, indent=2), content_type='application/json')
方式三、使用django
的序列化serializers
1、导包
from django.core import serializers from django.http import HttpResponse from django.views.generic import View from goods import models
2、视图类
class GoogView2(View): """ 定义一个产品视图 """ def get(self, request, *args, **kwargs): goods = models.GoodsModel.objects.all()[:10] json_data = serializers.serialize('json', goods) return HttpResponse(json_data, content_type='application/json')
方式四、直接返回json
1、导包
import json from django.core import serializers from django.http import HttpResponse, JsonResponse from django.views.generic import View from goods import models
2、视图类
class GoogView2(View): """ 定义一个产品视图 """ def get(self, request, *args, **kwargs): goods = models.GoodsModel.objects.all()[:10] json_data = serializers.serialize('json', goods) return JsonResponse(json.loads(json_data, encoding='utf-8'), safe=False)