-
Notifications
You must be signed in to change notification settings - Fork 10
DRF Filter
冒菜略寡味 edited this page May 11, 2018
·
8 revisions
大致扫了下RDF
文档的Filtering
一节,
了解到关于查询集queryset
的过滤,目前有两种方式:
- 通过覆写自定义
get_queryset()
方法过滤查询集; - 通过设置过滤器后端
filter_backend
方式过滤查询集;
第一种方式可以直接查阅文档了解,这里不做讲解,这里我们了解一下第二种通过过滤器后端的方式进行过滤;
$ pipenv install django-filter
# accountbook/settings.py
INSTALLED_APPS = [
...
'django-filters',
...
]
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',
)
# 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)
... 累到整夜不能睡,夜色哪裡都是美 ...
昨日擔當 昨日敢想
昨日轉眼 就跌撞
夏時夢長 秋時晝短
清冽途上 不遠望