程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

django-rest-framework - filter, search, sort, paginate

編輯:Python

一、過濾 filter

django-filterThe library includes oneDjangoFilterBackend類,它支持RESTFramework for highly customizable field filtering.
首先安裝django-filter, 然後將django_filters添加到Django的INSTALLED_APPS.
A default return can be set,在settings.py加上如下配置:

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

Or add filters to a single oneView或ViewSet中(一般使用這種):

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet
class UserListView(ModelViewSet):
...
filter_backends = (DjangoFilterBackend,)

If you want to allow filtering on certain fields,可以使用filter_fields屬性

from rest_framework.viewsets import ModelViewSet
from django_filters.rest_framework import DjangoFilterBackend
from myapp.models import Product
from myapp.serializers impoert ProductSerializer
class ProductList(ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('category', 'in_stock')
# filter_class = ProductFilter (Specifies the filter collection class)

You can also customize filter classes,再用filter_classSpecifies the filter collection class

import django_filters
from myapp.models import Product
from rest_framework import filters
class ProductFilter(filters.FilterSet):
min_price = django_filters.NumberFilter(name=’price’, lookup_type=”gte”)
max_price = django_filters.NumberFilter(name=’price’, lookup_type=”lte”)
# 行為: The name contains a certain character,And the characters are not case sensitive
name = filters.CharFilter(name='name', lookup_expr='icontains')
class Meta:
model = Product
fields = [‘category’, ‘in_stock’, ‘min_price’, ‘max_price’]

二、搜索 search

If you want to explicitly specify which fields can be searched on,可以使用search_fields屬性,Default is OKserializer_classAny readable field on the serializer specified by the property is searched:

from django.contrib.auth.models import User
from rest_framework import viewsets
from core.serializers import UserSerializer
from rest_framework import filters
class UserListView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'email')

Double underscores can also be usedForeign Key或ManyToManyField上執行相關查找:

search_fields = ('username', 'email', 'profile__profession')

三,排序 order

OrderingFilterThe class supports simple query parameters to control result ordering.
默認情況下,查詢參數被命名為“ordering”,But this may beORDERING_PARAM設置覆蓋.
可以使用ordering_fieldsProperties explicitly specify which fields can be sorted on,這有助於防止意外的數據洩露,For example allowing users to sort on password hash fields or other sensitive data.
如果不指定ordering_fields屬性,The default is yesserializer_classAny readable fields on the serializer specified by the property are filtered.

from django.contrib.auth.models import User
from rest_framework import viewsets
from core.serializers import UserSerializer
from rest_framework import filters
class UserListView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')

使用orderingThe property sets the default ordering(加"-"The minus sign can be used for flashbacks):
ordering = (’-id’,)

四、分頁 pagination

可以直接在view.pyCustom pagination rules in

from rest_framework.pagination import PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
"""
Configure pagination rules
"""
page_size = 12
page__size_query_param = 'page_size'
page_query_param = 'page'
max_page_size = 100

applied to the view function:

class UserListView(viewsets.ModelViewSet):
....
pagination_class = StandardResultsSetPagination
....

可以setting全局設置:

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'
}
  • PageNumberPaginationThe class includes many properties that can be overridden to modify the pagination style,要設置這些屬性,should coverPageNumberPagination類,Then enable the custom pagination class as shown above.

  • django_paginator_class:使用的Django
    Paginator類,默認是django.core.paginator.Paginator,Suitable for most use cases.

  • page_size:數值,頁面大小,默認是全局PAGE_SIZE的值.

  • page_query_param:字符串,查詢參數的名稱,默認是’page’

  • page_size_query_param:字符串,The parameter name for requesting to set the page size,默- 認是None,表示客戶端可能無法控制請求的頁面大小.

  • max_page_size:字符串,Maximum allowed requested page size, 此屬性僅在page_size_query_paramAlso valid when set.

  • last_page_strings:A list or tuple of strings,默認是(‘last’,)

  • template:The name of the template used by the paging control,Can be overridden or set toNone,默認為"rest_framework/pagination/numbers.html"


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved