文章目录
- 安装
- 配置sttings
- 自定义过滤类
- 指定过滤字段和过滤类
安装
pip insall django-filter
配置sttings
INSTALLED_APPS = [
...
'django_filters',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS':
('django_filters.rest_framework.DjangoFilterBackend',)
}
自定义过滤类
from django_filters import rest_framework as filters
from App.models import Bookinfo
class BookFilter(filters.FilterSet):
comment = filters.NumberFilter(field_name='bcomment', method='find_comment')
class Meta:
model = Bookinfo
fields = {
'btitle':['icontains','startswith','iendswith'],
'bread':['exact','lt','gt','lte','in'],
}
def find_comment(self,queryset,name,value):
"""
:param queryset:
:param name: 查询字段名
:param value: 查询的值
:return: queryset(一定要返回queryset)
"""
print(name,value)
return queryset.filter(bcomment__lt=value)
指定过滤字段和过滤类
class BooksView(ListAPIView):
"""
图书分页显示
"""
queryset = Bookinfo.objects.all()
serializer_class = BookinfoSerializer
filter_fields = ('btitle','bread')
filter_class = BookFilter