django rest framework使用django-filter实现过滤和搜索

首先创建一个models.py

from django.db import models

LANGUAGE_CHOICES = (
    ('0' , 'python'),
    ('1' , 'java')
)
STYLE_CHOICES =(
    ('0' , 'friendly'),
    ('1' , 'lovely')
)

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ('created',)

再创建filters.py

import django_filters
from rest.models import Snippet


class SnippetFilter(django_filters.FilterSet):
    class Meta():
        model = Snippet
        fields = ['id', 'language']

在view.py中添加过滤

class SnippetView(viewsets.ModelViewSet):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializers
    filter_class = SnippetFilter
    search_fields = ('title', '=style',) #在这里添加可以搜索的字段

url.py中配置路由:

urlpatterns = [
url(r'^api/', SnippetView.as_view({'get': 'list', 'post': 'create'}))
]

注:
需要先pip install django_filter 和 pip install django_filters
然后在settings.py中配置:

INSTALLED_APPS = [
	...
    'django_filters',
]

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ( 
'django_filters.rest_framework.DjangoFilterBackend',  # 过滤功能
'rest_framework.filters.SearchFilter',   # 搜索功能
'rest_framework.filters.OrderingFilter',  # 排序功能
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', # 分页功能
'PAGE_SIZE': 100  # 一页可现实数据条数
}

最后可以通过路由:

127.0.0.1:8080/rest/api/?id=1  #过滤得到id=1的数据
127.0.0.1:8080/rest/api/?search=friendly   # 搜索得到包含friendly的数据
127.0.0.1:8080/rest/api/?limit=1&offset=2   # 获取的数据每页显示一条,跳转到第三页的数据

返回得到id为1的数据

你可能感兴趣的:(Django,restframework)