安装
1
| pip install django-filter
|
注册进 Django
vim settings.py
1 2 3 4 5 6 7 8 9 10
| INSTALLED_APPS = [ ... 'django_filters', ]
REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], }
|
视图中单独指定
1 2 3 4 5 6 7 8 9 10
|
from django_filters.rest_framework import DjangoFilterBackend
class ArticleViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ['author__username', 'title']
|
使用
上面指定了过滤的字段,那么可以根据这两个字段进行过滤了。
1
| curl http://localhost:8000/api/article/?author__username=iuxt&title=
|
模糊搜索
上面的搜索(过滤)方式是精确搜索, 如果你使用的是 DRF,需要模糊搜索可以使用 rest_framework
的 filters
vim views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ... from rest_framework import filters
class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer permission_classes = [IsAdminUserOrReadOnly]
filter_backends = [filters.SearchFilter] search_fields = ['title']
|
搜索方式
1
| curl http://localhost:8000/api/article/?search=测试测
|