django rest framework mixins

 

 

ViewSetMixin:

重写了as_view方法,

1.获取到HTTP的请求方法
2.为我们提供了绑定的功能,如下图

 

现在我们来一一介绍:

ListModelMixin:

list 函数我们一般不重写

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)

  

CreateModelMixin:

这里我们可以在perform_create方法中新增我们的逻辑,完成对数据的操作。

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()
        # serializer.save(user=self.request.user)

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

 

  此处有一个坑,request.data QueryDict是不可修改的,解决办法就是复制一份副本,对副本进行修改,解决password明码存储问题。  

from django.contrib.auth.hashers import make_password
data = request.data.copy()
data['password'] = make_password(data['password'])
serializer = self.get_serializer(data=data)

RetrieveModelMixin:

class RetrieveModelMixin(object):
    """
    Retrieve a model instance.
    """
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        ###
        # 此处添加业务逻辑
        # instance.click_num += 1
        # instance.save()
        ### 
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

  

UpdateModelMixin:

同createModelMixin,尽量修改perform_update方法,不要修改update方法

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)


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()

  

posted @ 2019-03-08 11:00  家迪的家  阅读(645)  评论(0编辑  收藏  举报