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-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_class
from .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’)

Ordering

同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,usernameapp

相關文章
相關標籤/搜索