Django-rest-framework(六)filter,ordering,search

filter

queryset 使用request.user相关的queryset

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        返回purchaser 是request.user的queryset
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

对queryset 做简单的filter 操作

import django_filters.rest_framework
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # filter 操作依赖于filter_backends,所以需要先指定backends
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    # 指定filter 的字段
    filter_fields = ('category', 'in_stock')

自定义filter

需要依赖第三方库django-filter

  • 安装: pip install django-filter
  • settings.py中 添加INSTALLED_APPS = [...,'django_filters',...]
  • 创建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='gt')
    type = filters.CharFilter(method='filter_type') # 指定对应的方法

    def filter_type(self, queryset, name, value):
        #多选项,由,号分割
        return queryset.filter(feature__in=value.split(","))

    class Meta:
        model = Goods
        fields = ['min_price', ‘type’, 'status']
  • views.py文件中加入filter_class

from .filters import GoodsFilter

class xxView(xxxView):
    filter_class = GoodsFilter

我们用drf自带的SearchFilter可以实现该功能

from rest_framework import filters

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # backends 中加入SearchFilter 才能激活搜索,字段为 search
    filter_backends = (filters.SearchFilter,)
    search_fields = ('username', 'email',‘profile__profession’)

Ordering

同search一样,需要drf自带的OrderingFilter。使用方法如下

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # backend 中加入OrderingFilter 激活ordering filter,字段为ordering
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('account', 'username', 'email')
    # 指定默认的排序字段
    ordering = ('username',)

如果需要取倒序,可以在字段前加“-” 如 http://example.com/api/users?ordering=-username, 如果需要多个排序的,可以使用“,”分隔 如:http://example.com/api/users?ordering=account,username

posted @ 2019-02-14 10:09  余震杰yzj  阅读(3066)  评论(0编辑  收藏  举报