欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Restframework的

程序员文章站 2022-05-04 11:28:36
...

Restframework对view进行了多层封装,封装层数越多,越不灵活
点击查看官方文档

  • View (最底层的view)

#底层view
from django.views.generic.base import View

from goods.models import Goods

class GodsListView(View):
   def get(self,request):
       """
       t通过django的view实现商品列表页
       :param request:
       :return:
       """
       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_list.append(json_dict)


       # from django.forms.models import model_to_dict
       # for good in goods:
       #     json_dict = model_to_dict(good)
       #     json_list.append(json_dict)
       #
       from django.http import HttpResponse,JsonResponse
       import json
       from django.core import serializers
       json_data = serializers.serialize("json",goods)
       json_data = json.loads(json_data)
       return JsonResponse(json_data,safe=False)

  • APIView (继承底层view,进行封装,一般用的较多)
from rest_framework.views import APIView
from rest_framework.response import Response

class GoodsListView(APIView):
   """
   商品列表
   """
   def get(self,request,format=None):
       goods = Goods.objects.all()[:10]
       goods_serializer = GoodsSerializer(goods,many=True)
       return Response(goods_serializer.data)

   def post(self,request,format=None):
       serilizer = GoodsSerializer(data=request.data)
       if serilizer.is_valid():
           serilizer.save()
           return Response(serilizer.data,status=status.HTTP_201_CREATED)
       return Response(serilizer.errors,status=status.HTTP_400_BAD_REQUEST)
  • mixins、generics封装简化代码
from rest_framework import mixins
from rest_framework import generics

class GoodsListView(mixins.ListModelMixin,generics.GenericAPIView):
    """
    商品列表页
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)
  • ListAPIView 将上面的方法再次封装,使代码更加简洁
     class ListAPIView(mixins.ListModelMixin,GenericAPIView)
from rest_framework import generics

class GoodsListView(generics.ListAPIView):
    """
    商品列表页
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
相关标签: View