过滤、排序和异常处理
一、过滤
1. 基本使用
1.1 安装
| pip3 install django-filter
|
1.2 注册
| # settings.py
INSTALLED_APPS = [
...
'django_filters'
]
|
1.3 全局配置
| # settings.py
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
|
1.4 视图类中添加过滤字段
| class BooksView(ListAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
filter_fields = ('price',) # 配置可以按照哪个字段来过滤
|
二、排序
1. 基本使用
局部使用:
| from rest_framework.filters import OrderingFilter
class BooksView(ListAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
filter_backends = [OrderingFilter]
ordering_fields = ('id', 'price')
|
访问:http://127.0.0.1:8000/books/?ordering=price
三、异常处理
1. 基本使用
1. 配置
| # settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app.utils.my_exception_handler',
}
|
2. 定义异常处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | 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)
# 两种情况:
# 1. drf没有处理,返回None
# 2. response对象,django处理了,但是处理的不符合项目的要求
if not response:
if isinstance(exc, ZeroDivisionError):
return Response(data={'status': 70003, 'msg': "除以0的错误" + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
return Response(data={'status':30002,'msg':str(exc)},status=status.HTTP_400_BAD_REQUEST)
else:
# return response
return Response(data={'status':40012,'msg':response.data.get('detail')},status=status.HTTP_400_BAD_REQUEST)
|