django 视图GenericView

from rest_framework.generics import GenericAPIView
from .models import Student,TeacherClass,Teacher,Class
from  .serializers import SerializerStudent
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK



class  StudentGenericView(GenericAPIView):
    queryset = Student.objects.filter(is_delete=False).all()
    serializer_class = SerializerStudent

    def get(self,request,pk):
        if pk :
            student=self.get_object() # one row
            serializer=SerializerStudent(instance=student)
            return Response(data=serializer.data,status=HTTP_200_OK)

        else:
            students=self.get_queryset() # all rows
            serializer=SerializerStudent(instance=students,many=True)
            return Response(data=serializer.data,status=HTTP_200_OK)

    def post(self,request,*args,**kwargs):
        serializer=SerializerStudent(data=request.data)
        if serializer.is_valid():
            serializer.save()
            data,status=serializer.data,200
        else:
            data,status=serializer.errors,400

        return  Response(data=data,status=status)


    def put(self,request,pk):
        student=self.get_object()
        serializer=SerializerStudent(instance=student,data=request.data)
        if serializer.is_valid():
            serializer.save()
            data=serializer.data
        else:
            data=serializer.errors
        return Response(data=data, status=HTTP_200_OK)

    def delete(self,request,pk):
        if pk :
            instance=self.get_object()
            instance.is_delete=True
            instance.save()
            serializer=SerializerStudent(instance=instance)
            return Response(data=serializer.data)

 以上是基于GenericView实现增删改查,实现是单个查询借助self.get_object()以及路由pk进行查询,批量所有数据集合借助queryset,序列化器借助serializer_class

源码解析:

 

class GenericAPIView(views.APIView):
"""
Base class for all other generic views.它是其他所有generic的视图的基类视图,提供了self.get_serializer_class 方法,self.get_object方法
  其次继承了Apiview,dispatch inital 方法

"""
# You'll need to either set these attributes,
# or override `get_queryset()`/`get_serializer_class()`.
# If you are overriding a view method, it is important that you call
# `get_queryset()` instead of accessing the `queryset` property directly,
# as `queryset` will get evaluated only once, and those results are cached
# for all subsequent requests.
queryset = None
serializer_class = None

# If you want to use object lookups other than pk, set 'lookup_field'.
# For more complex lookup requirements override `get_object()`.
lookup_field = 'pk'
lookup_url_kwarg = None

# The filter backend classes to use for queryset filtering
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS

# The style to use for queryset pagination.
pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

generic 视图方法包括以下几个

 

 mixmin里面实现了几个重要mixmin类基于list,update,destroy,create 方法:

 

 在五个基本的generic 视图类身上又进一步多继承实现了更加简单丰富的类方法:

 

 

modelviewset:

from rest_framework.viewsets import ViewSet,GenericViewSet,ModelViewSet
源码解读:

 

 

 

 url.py

urlpatterns = [
    url(r'^student/$',model_view.StudentModelView.as_view({"get":"list","post":"create"})),
    url(r'^student/(?P<pk>.*)$', model_view.StudentModelView.as_view({"get": "retrieve",
                                                                      "put": "update","delete":"destroy"})),

]

 

Response 代码解读:

第一步调用get_objectc查询对象:

 

 

第二步:没找到就报Http404

 

posted @ 2020-10-25 01:12  不带R的墨菲特  阅读(306)  评论(0编辑  收藏  举报