Django和DRF的View层获取JSON的方式
调用方法
都是导入urls.py的urlpatterns里配置使用:
path(r'goods/', GoodsListView.as_view(), name="goods-list"),
Django方式
创建一个views_base.py,里面:
# encoding: utf-8 from goods.models import Goods # Django cpv方式最底层的view from django.views.generic.base import View
class GoodsListView(View): def get(self, request): """ 通过django的view实现商品列表页 """ json_list = [] goods = Goods.objects.all()[:10] # for good in goods: # json_dict = {} # json_dict["name"] = good.name # json_dict["category"] = good.category.name # json_dict["market_price"] = good.market_price # json_dict["add_time"] = good.add_time # json_list.append(json_dict) # from django.http import HttpResponse # import json # return HttpResponse(json.dumps(json_list),content_type="application/json") from django.forms.models import model_to_dict for good in goods: json_dict = model_to_dict(good) json_list.append(json_dict) import json from django.core import serializers json_data = serializers.serialize('json', goods) json_data = json.loads(json_data) from django.http import HttpResponse, JsonResponse # jsonResponse做的工作也就是加上了dumps和content_type # return HttpResponse(json.dumps(json_data), content_type="application/json") # 注释掉loads,下面语句正常 # return HttpResponse(json_data, content_type="application/json") # 返回的不为dict时要设置safe=False return JsonResponse(json_data, safe=False)
DRF方式
自定义model的序列化器,在serializers.py:
from rest_framework import serializers class GoodsSerializer(serializers.Serializer): def update(self, instance, validated_data): pass def create(self, validated_data): pass name = serializers.CharField(required=True, max_length=100) click_num = serializers.IntegerField(default=0)
在views.py:
from rest_framework.views import APIView from rest_framework.response import Response from .serializers import GoodsSerializer from .models import Goods class GoodsListView(APIView): def get(self, response, format=None): goods = Goods.objects.all()[:10] goods_serializer = GoodsSerializer(goods, many=True) return Response(goods_serializer.data)
其中DRF方式更强大,在浏览器请求下会直接返回一个易读的HTML而不是JSON。可以用Postman再试试。