django restframeowrk filter,search,order

django-filters非常成熟,并且支持drf,在url中以Get参数的形式体现

filter

通用过滤

1. 基本配置

$ pip install django-filters

settings.py

INSTALLED_APPS = [
......
'django_filters'
]

views.py

from django_filters.rest_framework import DjangoFilterBackend
# 注意点,继承viewsets.GenericViewSet
filter_backends = (DjangoFilterBackend, )
filter_fields = ('username',)

当然我们也可以自行通过current user,url, query parameters过滤

    def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Purchase.objects.all()
username = self.request.query_params.get('username', None)
if username is not None:
queryset = queryset.filter(purchaser__username=username)
return queryset

  优点:满足任何需求。 缺点:需要写较多代码。

2. 进阶

通常在对应app下创建filters.py

import django_filters

from .models import Goods

class GoodsFilter(django_filters.rest_framework.FilterSet):
min_price = django_filters.NumberFilter(name='shop_price', lookup_expr='gte')
max_price = django_filters.NumberFilter(name='shop_price', lookup_expr='lte') class Meta:
model = Goods
fields = ['min_price','max_price']

  

1. name 代表Model中的字段
2. lookup_expr而是djangoORM查询提供的查询方法(gt等于model.objects.filter(xx__gt=xx))

views.py中使用filter_class

filter_class = GoodsFilter

  

Search

搜索功能使用的是Drf自带的内容。Drf将搜索功能也融入了filter中,所以配置与filter类似。

在filter_backends中加入搜索功能

from rest_framework import filters

filter_backends = (DjangoFilterBackend,filters.SearchFilter)

指明查询字段

search_fields = ('username',)

源码:提供了四种查询方式,准确查询就用=

class SearchFilter(BaseFilterBackend):
# The URL query parameter used for the search.
search_param = api_settings.SEARCH_PARAM
template = 'rest_framework/filters/search.html'
lookup_prefixes = {
'^': 'istartswith',
'=': 'iexact',
'@': 'search',
'$': 'iregex',
}
search_title = _('Search')
search_description = _('A search term.')

  

Order

排序同搜索

filter_backends = (DjangoFilterBackend,filters.OrderingFilter)

ordering_fields = ('id',)

  

上一篇:章节十一、1-Junit介绍


下一篇:EhReport ,CReport改进版本,再次改进 ,V1.31