Skip to content

DRF Filter

冒菜略寡味 edited this page May 11, 2018 · 8 revisions

DRF 查询过滤

大致扫了下RDF文档的Filtering一节, 了解到关于查询集queryset的过滤,目前有两种方式:

  1. 通过覆写自定义get_queryset()方法过滤查询集;
  2. 通过设置过滤器后端filter_backend方式过滤查询集;

第一种方式可以直接查阅文档了解,这里不做讲解,这里我们了解一下第二种通过过滤器后端的方式进行过滤;

1. 安装django-filter库:

$ pipenv install django-filter

2. 项目配置中添加该库应用:

# settings.py
INSTALLED_APPS = [
    ...
    'django-filters',
    ...
]

3. 视图中的设置:

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from apps.bills.filters import BillsFilter

class BillsViewSet(viewsets.ModelViewSet):
    serializer_class = BillSerializer
    permission_classes = (IsAuthenticated,)
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = BillsFilter
    ordering_fields = ('amount', 'record_date')

https://chown-jane-y.github.io/2017/09/13/Django-REST-framework%E9%81%87%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98-%E4%BA%8C/

昨日擔當 昨日敢想

昨日轉眼 就跌撞

夏時夢長 秋時晝短

清冽途上 不遠望

Clone this wiki locally