Django view extended class

Django view extended class

With extended class must GenericAPIViewuse the extended internal class, when calling serializer, are usingget_serializer

Need to customize get, postand other request methods, the internal implementation calls the corresponding method to extend the class.

A, mixins view subclass

effect:

It provides several back-end view (deletion of data resources has been checked) to achieve processing flow, if you need to write views belong to these five, you can view the code reuse through inheritance corresponding extension classes, reduce code I have written the amount.

The five extended by the need to match GenericAPIViewthe parent class, because the realization of five extension class needs to call GenericAPIViewa method with the sequence of database queries provided.

1.1 ListModelMixin

Extension class list view, there is provided list(request, *args, **kwargs)method to quickly list view 200 returns a status code.

  1. Provide listmethods to achieve quick list view
  2. Call to GenericAPIViewset a good set of results
  3. Call to GenericAPIViewset a good serializer

That Mixinthe list()method will filter the data and paging.

Source:

from rest_framework.mixins import ListModelMixin

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        # 过滤
        queryset = self.filter_queryset(self.get_queryset())
        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        # 序列化
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

For example:

from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView

class BookListView(ListModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request):
        return self.list(request)

1.2 CreateModelMixin

Creating the view extension class that provides create(request, *args, **kwargs)a method to quickly realize the resources to create a view, a successful return 201 status code.

  1. Provide create(request, *args, **kwargs)a method to quickly achieve the creation of resource view
  2. The actual sequence created by the function of the savecomplete method
  3. saveThe method calls will go to serialize's createmethod

If the sequence of the authentication failure of the data transmission of the front end, returns 400 an error.

Source:

from rest_framework.mixins import CreateModelMixin

class CreateModelMixin(object):
    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        # 获取序列化器
        serializer = self.get_serializer(data=request.data)
        # 验证
        serializer.is_valid(raise_exception=True)
        # 保存
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

1.3 RetrieveModelMixin

Extension class detail view, there is provided retrieve(request, *args, **kwargs)a method, it can be implemented quickly return to a present data object.

If so, return to 200, otherwise 404.

Source:

from rest_framework.mixins import RetrieveModelMixin

class RetrieveModelMixin(object):
    """
    Retrieve a model instance.
    """
    def retrieve(self, request, *args, **kwargs):
        # 获取对象,会检查对象的权限
        instance = self.get_object()
        # 序列化
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

For example:

from rest_framework.mixins import RetrieveModelMixin
from rest_framework.generics import GenericAPIView

class BookDetailView(RetrieveModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request, pk):
        return self.retrieve(request)

1.4 UpdateModelMixin

Update the view extension class is provided update(request, *args, **kwargs)a method

  1. It can be implemented quickly update an existing data object.
  2. It also provides partial_update(request, *args, **kwargs)methods may be implemented partial update.
  3. Internal update function calls deserializer savemethod
  4. saveMethod calls the serializer's updatemethod

200 successful return, when the data serializer check fails, returns 400 an error.

Source:

from rest_framework.mixins import UpdateModelMixin

class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

1.5 DestroyModelMixin

Delete View extension class is provided destroy(request, *args, **kwargs)a method, it can be implemented quickly delete an existing data object.

The successful return of 204, 404 there is no return.

Source:

from rest_framework.mixins import DestroyModelMixin

class DestroyModelMixin(object):
    """
    Destroy a model instance.
    """
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.delete()

Use GenericAPIViewand extended view class that implements apithe interface, the code:

"""GenericAPIView结合视图扩展类实现api接口"""
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin

class Students2GenericAPIView(GenericAPIView,ListModelMixin,CreateModelMixin):
    # 本次视图类中要操作的数据[必填]
    queryset = Student.objects.all()
    # 本次视图类中要调用的默认序列化器[玄天]
    serializer_class = StudentModelSerializer

    def get(self, request):
        """获取多个学生信息"""
        return self.list(request)

    def post(self,request):
        """添加学生信息"""
        return self.create(request)

from rest_framework.mixins import RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.generics import GenericAPIView

class Student2GenericAPIView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = Student.objects.all()

    serializer_class = StudentModelSerializer

    # 在使用GenericAPIView视图获取或操作单个数据时,视图方法中的代表主键的参数最好是pk
    def get(self,request,pk):
        """获取一条数据"""
        return self.retrieve(request,pk)

    def put(self,request,pk):
        """更新一条数据"""
        return self.update(request,pk)

    def delete(self,request,pk):
        """删除一条数据"""
        return self.destroy(request,pk)

Two, Generic view subclass

2.1 CreateAPIView

Provide postmethods

Inherited from: GenericAPIView`CreateModelMixin

2.2 ListAPIView

Provide getmethods

Inherited GenericAPIViewfrom: ,ListModelMixin

2.3 RetrieveAPIView

Provide getmethods

Inherited GenericAPIViewfrom: ,RetrieveModelMixin

2.4 DestoryAPIView

Provide deletemethods

Inherited GenericAPIViewfrom: ,DestoryModelMixin

2.5 UpdateAPIView

Provided putand patchmethods

Inherited GenericAPIViewfrom: ,UpdateModelMixin

2.6 RetrieveUpdateAPIView

Provided get, put, patchmethod

Inherited GenericAPIViewfrom: RetrieveModelMixin, ,UpdateModelMixin

2.7 RetrieveUpdateDestoryAPIView

Provide get, put, patch, deletemethod

Inherited GenericAPIViewfrom: RetrieveModelMixin, UpdateModelMixin, ,DestoryModelMixin

Guess you like

Origin www.cnblogs.com/Dr-wei/p/11735509.html