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)
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')
須要依賴第三方庫django-filterpython
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_classfrom .filters import GoodsFilter class xxView(xxxView): filter_class = GoodsFilter
咱們用drf自帶的SearchFilter
能夠實現該功能django
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’)
同search同樣,須要drf自帶的OrderingFilter
。使用方法以下api
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
app