Skip to content

1、也可以继承CustomModelViewSet进行自定义重写list、create、update方法(处理一些低逻辑纯展示)

from utils.viewset import CustomModelViewSet

class AreaViewSet(CustomModelViewSet):
    """
    地区管理接口:
    list:查询
    create:新增
    update:修改
    """
    queryset = Area.objects.all().order_by('id')
    serializer_class = AreaSerializer
    filter_fields = ['status','id','parent']
    search_fields = ('name',)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return SuccessResponse(data=serializer.data, msg="新增成功")

    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, request=request)
            return self.get_paginated_response(serializer.data)
            # result = self.get_paginated_response(serializer.data)
            # print(51,result.data)
            # return JsonResponse(code=2000,msg="获取成功", data=result.data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, request=request, 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 = {}

Released under the Apache License 2.0