DRF过滤 排序 异常处理 封装Response

过滤

# 1 安装 pip install django-filter
# 2 注册,在app中注册
# 3 全局配,或者全局配
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
# 4 视图类:
class BookView(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_fields = ('name',)  # 配置可以按照哪个字段来过滤

 

排序

# 局部使用和全局使用
# 局部使用
from rest_framework.filters import OrderingFilter
class BookView2(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ('id', 'price')  # 注意要配置
# urls.py:
path('books2/', views.BookView2.as_view()),
# 使用:
http://127.0.0.1:8000/books2/?ordering=-price
http://127.0.0.1:8000/books2/?ordering=price

 

异常处理

# 统一接口返回

# 自定义异常方法,替换掉全局
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status


def my_exception_handler(exc, context):
    response = exception_handler(exc, context)
    # 两种情况,一个是None,drf没有处理
    # response对象,django处理了,但是处理的不符合咱们的要求

    if not response:
        if isinstance(exc, ZeroDivisionError):
            return Response(data={'status': 777, 'msg': '除以0的错误' + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(data={'status': 999, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)
    else:
        # return response
        return Response(data={'status': 888, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)

# 全局配置settings.py
'EXCEPTION_HANDLER': 'app01.app_auth.my_exception_handler',

 

封装Response对象

# 以后都用自己封装Response对象  app_auth.py
from rest_framework.response import Response

class APIResponse(Response):
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None,**kwargs ):
        dic = {'code': code, 'msg': msg}

        if data:
            dic = {'code': code, 'msg': msg, 'data': data}
        dic.update(kwargs)
        super().__init__(data=dic, status=status, headers=headers)
        
# views.py: 使用
# 自定义返回对象
from app01.app_auth import APIResponse

class TestView7(APIView):
    def get(self, request, *args, **kwargs):
        return APIResponse(data={'name': 'lqz'}, token='argargaedasads')

 

posted @ 2021-06-11 17:15  Palpitate~  阅读(19)  评论(0编辑  收藏  举报