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. 项目配置中添加该库应用:

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

3. 创建过滤器:

from django_filters import rest_framework as filters
from apps.bills.models import Bills

class BillsFilter(filters.FilterSet):
    """
    账目过滤器
    """
    bill_type = filters.NumberFilter(name='bill_type')
    min_amount = filters.NumberFilter(name='amount', lookup_expr='gte')
    max_amount = filters.NumberFilter(name='amount', lookup_expr='lte')
    start_date = filters.DateFilter(name='record_date', lookup_expr='gte')
    end_date = filters.DateFilter(name='record_date', lookup_expr='lte')
    remarks = filters.CharFilter(name='remarks', lookup_expr='icontains')

    class Meta:
        model = Bills
        fields = (
            'category',
            'bill_type',
            'min_amount',
            'max_amount',
            'start_date',
            'end_date',
        )

4. 视图中的设置:

# apps/bills/views.py
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')
    
    # 覆写查询集,仅查询当前用户下的账目数据
    def get_queryset(self):
        return Bills.objects.filter(user=self.request.user)

commit: 61b0f8f95db64784c5c5710790059d31b175bcbd

昨日擔當 昨日敢想

昨日轉眼 就跌撞

夏時夢長 秋時晝短

清冽途上 不遠望

Clone this wiki locally