DRF序列化之GenericView

前面我们通过ModelSerializer实现了复杂的嵌套式序列化。是不是DRF就只有这一点功能呢?我们的代码还能不能再简洁一点呢?答案是肯定是、哈哈哈(为什么每次答案都是肯定的?)我们不再使用APIView来实现我们上面讲到的功能。我们会使用一些DRF更加高级的View方法:GenericView里面的mixins.ListModelMixin以及generics.GenericAPIView。GenericAPIView是一个非常重要的View、他在APIView的基础上进行了二次封装、帮助我们实现了很多功能、比如:queryset,serializer_class,filter_backends,pagination_class等等。

from .models import Goods
from goods.serializers import GoodsSerializer
from rest_framework import mixins
from rest_framework import generics


# Create your views here.
class GoodsList(mixins.ListModelMixin, generics.GenericAPIView):
    """
   商品列表页
   """
    queryset = Goods.objects.all()[:10]
    serializer_class = GoodsSerializer
    
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

写完之后我们就可以重启项目刷新页面、我们可以看到数据已经正常返回了。

既然GenericAPIView功能这么强大、那还有没有更加简洁的方法呢?实际上GenericAPIView为我们提供了很多方法,比如:CreateAPIView,ListAPIView,RetrieveAPIView,DestroyAPIView,UpdateAPIView等等。我们可以直接继承这些方法即可。

from .models import Goods
from goods.serializers import GoodsSerializer
from rest_framework import mixins
from rest_framework import generics


# Create your views here.
class GoodsList(generics.ListAPIView):
    """
   商品列表页
   """
    queryset = Goods.objects.all()[:10]
    serializer_class = GoodsSerializer

推荐文章

4条评论

  1. It is not my first time to pay a visit this web site, i am browsing this site dailly and obtain nice data from here all the time. Manon Chrissie Mini

  2. Hello, I want to subscribe for this weblog to take latest updates, therefore where can i do it please help. Rafaelia Arnold Georgianna

  3. I was reading through some of your blog posts on this internet site and I think this web site is real informative ! Retain posting . Peggie Goran Rosecan

  4. I am sure this paragraph has touched all the internet people, its really really fastidious paragraph on building up new website. Tasia Leonhard Lange

发表评论

邮箱地址不会被公开。 必填项已用*标注