Django REST framework data display skills: practical configuration and practice of paging, filtering and search

A directory of articles in the series

  • Getting Started with Django: Building Your First Web Project from Scratch
  • Getting Started with Django ORM: From concept to practice, master model creation, migration, and view manipulation
  • Django ORM Practice: Model Field and Meta Option Configuration, as well as Chain Filtering and QF Query
  • Django ORM Deep Tour: Exploring the Mystery and Practice of Many-to-One, One-to-One and Many-to-Many Data Relationships
  • Cross-domain issues and Django solutions: In-depth analysis of cross-domain principles, request handling, and CSRF protection
  • Django View Layer Exploration: GET/POST Request Processing, Parameter Passing, and Response Modes
  • Django Routing and Session Deep Dive: Static and Dynamic Routing Distribution, and the Mystery of Cookies and Sessions
  • Django API Development Practice: Separation of Front and Back End, Restful Style and DRF Serializer
  • Django REST framework Serializer: Selection and Application of Common Serializer and Model Serializer
  • Django REST framework association serializer details: master the art of serialization and deserialization of complex relationships
  • GenericAPIView in Django REST framework and Detailed Explanation of Mixed Extension Class
  • Django REST framework View Set and Routing in Detail: In-depth Understanding of ViewSet, ModelViewSet, and Route Mapper
  • Django Middleware Exploration: Revealing the Daemon Role and Practical Application of Middleware in Web Applications
  • Django REST framework Data Presentation Skills: Practical Configuration and Practice of Paging, Filtering and Searching
  • Study hard 0.0ing …

Article Directory

  • A directory of articles in the series
  • Foreword
  • I. Paging
    • 1. Paging in Django view functions
    • 2. DRF Global Settings Paging
    • 3. DRF Local Settings Paging
    • 4. Using paging in APIView
    1. Filtration
    • 1. Precise filtering of django-filter
    • 2. Fuzzy filtering of django-filter
    • 3. Search Filter for rest \ _ framework
    1. Sorting
    • Ordering with Ordering-Filter

Foreword

    In this blog,We will analyze it in detail_Django REST frameworkCenter pagination、Filter and search definitions、Functions and how to use_。We will not only introduce how to set up and use the basic,We will also delve into how to perform global configuration and local configuration.,To meet the needs of different scenarios。

    _ Paging function _ allows us to divide the data into multiple pages according to our needs, ensuring that users don’t get confused or overloaded when browsing large amounts of data. _ Filtering function _ gives users finer control over the data they see, allowing them to quickly locate the information they need through preset conditions or custom queries. This ability is further enhanced by _ Search function _, which allows users to quickly retrieve relevant data through keywords.


I. Paging

_Think about it, why don’t we almost show all the data requested in the web page at one time? _

  • If the amount of data is quite small, such as only a few dozen, then in general, there is no need to worry about rendering it into the page.
  • But if the amount of data is relatively large, such as hundreds of thousands of tens of thousands, and once this operation is more frequent, it will obviously increase the server load, the main bottleneck is the database.

  Let’s not talk about how to achieve high concurrency here, but how to get and display data in a lightweight way.

_An effective way is to implement paging queries. _:
The operation of obtaining all data at one time is decomposed into multiple query operations, and only a part of data is queried and displayed in each operation. Where each query fetches a page of data.

1. Paging in Django view functions

_Paging effect in Django view function: _

#views.py
# 0.View function implements paging effect
def index(request):
    if request.method == 'POST':
        return JsonResponse({"message":"POSTTest list pagination"})
        # return HttpResponse('{"message":"Hello POST"}',content_type='application/json')
    elif request.method == 'GET':
        list1 = ["Zhang San","John Doe","Wang Wu","Zhao Liu","beginning of autumn","Li Qi","Bizarre",64,84,84,6,54,5,6,7]

        # Paginator(List data,Number of items)
        pagtor = Paginator(list1,3)

        # Get the query parameters of the front end:Number of pages requested,page number
        page = request.GET.get('page')

        print(page)
        data = pagtor.get_page(page)

        print(data.object_list)
        # return HttpResponse('{"message": data.object_list}',content_type='application/json')
        return JsonResponse({"message":"testGETList paging",'data': data.object_list}) 

_Notice _
JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
JsonResponse Is HttpRespon a subclass of, which differs from the parent class mainly in that:

  • Its default Content - Type is set to:
  • The first parameter ** data should be a dictionary type. When safe this parameter is set to False **, data can be filled with any object that can be converted to JSON format, such as list, tuple, set.
  • The ** default safe parameter is True **, and if the data type you pass in is not a dictionary type, it throws a TypeError exception.

2. DRF Global Settings Paging

Notice: Need to modify Django’s global configuration file

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3 #Number of data items per page
} 
 #views.py
class IndexView(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer 

3. DRF Local Settings Paging

_DRF customizes the paging class object and makes local paging settings: _

#views.py
#Import paginator class
from rest_framework.pagination import PageNumberPagination

# Partial paging configuration  Custom pager
class MyPaginator(PageNumberPagination):
    page_size = 2 # Quantity per page
    page_query_param = 'page' #query parameters:Parameter name of page number
    page_size_query_param = 'page_size' #query parameters,Parameter name for the number of pages per page
    max_page_size = 10 #maximum number per page

# http://localhost:8000/app01/indexview/?page=1&page_size=10
# 1.DRF Pagination
class IndexView(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer
    pagination_class = MyPaginator 

4. Using paging in APIView

The previous view functions that use built-in paging need to be inherited GenericAPIView, ListModelMixin (or directly inherit from ListAPIView). How to implement custom paging in a normal APIview?
    In fact, the steps are the same, except that APIView does not provide the encapsulation of data and methods. All operations need to be completed manually. Next, we can write our own inherited APIView view functions to implement paging.

class IndexView(APIView):
    def get(self,request):
        users = UserModel.objects.all()

        # Paginate the dataset,Custom pager
        # paginator = CommonPageNumberPagination()
        #Load system pager
        paginator = PageNumberPagination()

        #local settings,Configuration correspondencepage_sizeSize and corresponding parameterskey
        paginator.page_size = 2

        # Get paginated data
        qs = paginator.paginate_queryset(users, request, self)

        # Serialize data,Multiple pieces of data need to be added many=True
        res = UserSer(qs, many=True)

        # Return method one,Only return paginated results
        # return Response(res.data)

        # Return method two,Configure other information returned by yourself,For example, previous page, next page
        # return Response({
        #     'count': books.count(),
        #     'next': paginator.get_next_link(),
        #     'previous': paginator.get_previous_link(),
        #     'results': res.data
        # })

        # Return method three,Use the method to automatically return content similar to method 2
        return paginator.get_paginated_response(res.data) 

2. Filtration

In Django, django-filter is a powerful third-party application that provides a simple, flexible, and customizable filter system that allows developers to easily filter and sort Django query sets.

_ Filter _ allows users to filter data based on specific criteria. In Django, this usually means filtering the QuerySet.

1. Precise filtering of django-filter

_Use the steps _

  • Install the plug-in

The django-filter library includes a DjangoFilterBackend class that supports highly customizable field filtering for the REST framework.

** To use DjangoFilterBackend, install the django-filter **

pip install django-filter 
  • Register APP

** Added 'django_filters' to Django INSTALLED_APPS : **

#settings.py
INSTALLED_APPS = [
    ...
    'django_filters',
    ...
] 
  • Configure the filtering engine

_To add a filter backend to the global settings: _

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
} 

_Global Configuration Precise Filtering _

import django_filters.rest_framework
from rest_framework.generics import ListAPIView
from app.models import StudentModel
from app.serializer.studentSerializer import StudentSerializer

# 1. Precise filtering
class IndexFilterViews(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer

    filterset_fields = ['name','gender']

# filter
# http://localhost:8000/app01/indexfilter/?name=Zhang San
# http://localhost:8000/app01/indexfilter/?name=Zhang San&gender=1 

_Local configuration precision filtering _

import django_filters.rest_framework
from rest_framework.generics import ListAPIView
from app.models import StudentModel
from app.serializer.studentSerializer import StudentSerializer
# local configuration filter
from django_filters.rest_framework import DjangoFilterBackend

# 1. Precise filtering
class IndexFilterViews(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer
    filter_backends = [DjangoFilterBackend] 
    filterset_fields = ['name','gender']

# filter
# http://localhost:8000/app01/indexfilter/?name=Zhang San
# http://localhost:8000/app01/indexfilter/?name=Zhang San&gender=1 

2. Fuzzy filtering of django-filter

The default filter can realize the precise search function, but for some fields or data, fuzzy filtering needs to be realized in the development process, so it is necessary to customize the filter. Customize an advanced filter, the following is _ Customize the filter _

_Fuzzy filtering _

# views_filter.py
import django_filters.rest_framework
from rest_framework.generics import ListAPIView
from app.models import StudentModel
from app.serializer.studentSerializer import StudentSerializer
# local configuration filter
from django_filters.rest_framework import DjangoFilterBackend

# filter
# 2. blur filter
class StudentFilter(django_filters.rest_framework.FilterSet):
    """Custom filter class"""
    name = django_filters.CharFilter(field_name='name', lookup_expr='contains') 
    # field_name Indicates the field to be filtered;lookup_expr express What to do when filtering,
    # contains express Include,Used for blur filtering

    maxgt_age = django_filters.NumberFilter(field_name='age', lookup_expr='gte')
    minlt_age = django_filters.NumberFilter(field_name='age', lookup_expr='lte')
    class Meta:
        model = StudentModel
        fields = ['name','maxgt_age','minlt_age'] #query parameters,Database independent

class StudentVagueFilter(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer
    filter_backends = [DjangoFilterBackend] # local configuration filter
    filterset_class = StudentFilter # Specify filter class

http://127.0.0.1:8000/app/students/?name=plum 

3. Search Filter for rest \ _ framework

The SearchFilter of rest_framework is a filter backend class provided by the Django REST framework specifically for performing text search filtering in API views.

SearchFilter Allows the user to search for data in the query string by a specific parameter (the default is _ ** search ** _). This filter, based on the full-text search capability of the database (if available), performs a full-text search on the specified fields and returns results that match the specified search terms.

_ ** The search engine depends rest_framework on, no additional plugins ** need to be installed _

  • _Configure the search _

_To add a filter backend to the global settings: _

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['rest_framework.filters.SearchFilter']
} 

_Local Configuration/Global Configuration Search: _

from rest_framework.generics import ListAPIView
from app.models import StudentModel
from app.serializer.studentSerializer import StudentSerializer

# local configuration search
#from rest_framework.filters import SearchFilter

class IndexSearchView(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer
    # local configuration search
    # filter_backends = [SearchFilter]

    search_fields = ['name']
    # search_fields = ['^name'] surnamenameof
    # search_fields = ['=name'] exact match,fornameof
    ordering_fields = ['age']

http://127.0.0.1:8000/app/index/?search=Zhang San 

_ ** PS: Search behavior search_fields can be limited by adding various characters in front of characters: ** _

  • '^' Start the search
  • '=' An exact match
  • '$' Regular expression search

3. Sorting

Ordering with Ordering-Filter

Obtain the data according to certain Field requirements Order Sort. In fact, the _ ordering _ field can also be defined in _ model Model class _. The implementation of sorting actually uses Filtration some of the functions.

_ ** Implementation sort to use DRF the OrderingFilter provided implementation ** _

_Set filter backend (two ways) _

# 1.When configuring globally--settings.py
REST_FRAMEWORK = {

    'DEFAULT_FILTER_BACKENDS': ['rest_framework.filters.OrderingFilter']
}

# 2.When configuring locally---views_search.py 
  # import
  from rest_framework.filters import SearchFilter,OrderingFilter
  #view internal (The complete code is in the next code block)
  filter_backends = [filters.OrderingFilter] 

_The complete code of the views \ _ search. Py is as follows: _

# views_search.py
from rest_framework.generics import ListAPIView
from app.models import StudentModel
from app.serializer.studentSerializer import StudentSerializer

# local configuration(Guide package)  search
from rest_framework.filters import SearchFilter,OrderingFilter

class IndexSearchView(ListAPIView):
    queryset = StudentModel.objects.all()
    serializer_class = StudentSerializer

    # To be set during local configurationfilter_backends ,It is no longer necessary after global configuration.
    # filter_backends = [SearchFilter]
    filter_backends = [SearchFilter,OrderingFilter]

    search_fields = ['name']
    # search_fields = ['^name'] bynamebeginning,surname nameof
    # search_fields = ['=name'] exact match,for nameof
    ordering_fields = ['age']

http://127.0.0.1:8000/app/indexsearch/?ordering=-age # From big to small
http://127.0.0.1:8000/app/indexsearch/?ordering=age # From small to large