django-rest-framework中mixins.py的

2019-10-12  本文已影响0人  思绪太重_飘不动
from __future__ import unicode_literals

from rest_framework import status
from rest_framework.response import Response
from rest_framework.settings import api_settings


class CreateModelMixin(object):
     """
    CreateModelMixin对应的状态转化方法是: post 添加数据或修改数据 
    Create a model instance.
    """
    
    def create(self, request, *args, **kwargs):
        # 获取序列的数据
        serializer = self.get_serializer(data=request.data)
        """
            request.data: 获取前端传来的数据
            整段代码的意思: 获取前端的数据, 通过get_serializer()进行序列化
        """
        
        # 校验序列化后的前端数据
        serializer.is_valid(raise_exception=True)
        """
            is_valid: 校验数据
            raise_exception=True: 表示有异常就在这里抛出异常,如果为Flase表示没有异常,就继续执行下面的代码
        """
        
        # 保存数据
        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 {}


class ListModelMixin(object):
    """
    ListModelMixin对应的状态转化方法是: get 获取数据 
    List a queryset.
    """

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        """
            queryset:是我们主动获取的
            filter_queryset(): 过滤数据操作
            get_queryset():就是我们主动获取的数据
        """
        
        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            """
                get_serializer(): 获取序列化后的数据
            """
            return self.get_paginated_response(serializer.data)
        
        # 获取我们要序列化的数据, many=True 表示要序列化的数据有多个,并将这些数据系列化后,交由Response(serializer.data)返回
        serializer = self.get_serializer(queryset, many=True)

        # serializer.data 就是我们序列化后要返回的json数据
        return Response(serializer.data)


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)


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)


class DestroyModelMixin(object):
    """
    DestroyModelMixin: 销毁, 对应的状态转化方法: delete 销毁, 删除
数据
    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()
上一篇下一篇

猜你喜欢

热点阅读