Day 26 frequency type usage and sorting filtering

Day 26 frequency type usage

Configuration information search order

  • Partial configuration (priority) Partial configuration takes priority to partial configuration
  • Global configuration (second priority) Global configuration without default configuration
  • Default configuration (last) If there is no global configuration, go to the default configuration

One, the use of the choice field in the table

Choice receives a tuple (guaranteed that the value is immutable), and similarly, each option is also composed of a tuple **(value, display_name)**. Obviously, display_name is to be displayed on the page.

class Book(models.Model):
    name = models.CharField(max_length=32)
    author = models.ForeignKey(to='Author', on_delete=models.CASCADE)
    category = models.CharField(max_length=32, choices=(('1', '历史'), ('2', '政治'), ('3', '语文')))

image-20201111152513734

By default, our category field will only display the first type in the tuple, which is the string 1, 2, 3

 {
    
    
        "id": 1,
        "name": "python",
        "category": "1",
        "author": 1
    },

If we want to get the corresponding value "History", "Politics", "Language"Wait... we will use him for usAutomatic generated(You can use it directly after the database is migrated!) get_category_display

image-20201111154550310

Then we can use this method in the serializer

class BookSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source='get_category_display')
    
    class Meta:
        model = models.Book
        fields = "__all__"
        depth = 1

    {
    
    
        "id": 1,
        "category": "历史",
        "name": "python",
        "author": {
    
    
            "id": 1,
            "name": "李二狗",
            "address": "南湖大道"
        }
    },

Two, the use of multiple views

Third, the use of frequency

1. Custom frequency

2. Use of built-in rating

2.1.1 Partial use

Add the throttle_class attribute to the view class

throttle_classes = [auth.MyThrottle,]

2.1.2 Global use

Configure REST_FRAMEWORD = {} in settings and add key-value pairs of default rating

REST_FRAMEWORK = {
    
    
    	'DEFAULT_THROTTLE_CLASSES':['app01.MyThrottle.MyThrottle',],
		}

2.2 Extend the built-in frequency class

  • BaseThrottle : 基 类
  • SimpleRateThrottle: Let's customize and expand it
  • AnonRateThrottle: Limit the number of visits of anonymous users, distinguish users by IP address
  • ScopedRateThrottle: Limit the frequency of access to each view, distinguished by ip address or useid
  • UserRateThrottle: Limit the number of visits of logged-in users

The last three are his built-in access frequency restrictions, and the front is for us to expand.

2.3 Extend the built-in frequency class

from rest_framework.throttling import SimpleRateThrottle


class MyThrottle(SimpleRateThrottle):
    scope = '外比巴卜'
    
    def get_cache_key(self, request, view):
        
        return self.get_ident(request)  # 通过id限制

Then we configure in the setting

REST_FRAMEWORK = {
    
    
    'DEFAULT_THROTTLE_CLASSES': ['app01.MyThrottle.MyThrottle', ],
    
    'DEFAULT_THROTTLE_RATES': {
    
    '外比巴卜': '5/m'}  # key 与我们之前定义scope对应 value 是 次数/天/分/秒
}

image-20201111162402993

2.4 Read the source code

image-20201111171920359

Five, built-in, third-party filtering function (second focus)

1. Filter

Filter the list data according to the field

Use of built-in filters

  • Configure in the view class

    class BookView(GenericAPIView, ListModelMixin):
        queryset = Book.objects
        serializer_class = BookSerializer
        filter_backends = [SearchFilter]
        search_fields = ('name','id')  # 模型表中存在的字段
        
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    

    Execution process—>SearchFilter class—>get_search_fields—>must_call_distinct

    Query method

    The inherited method defaults toFuzzy query, Any related content will be queried!

    http://127.0.0.1:8000/books/?search=1

    image-20201111190649135

Third-party extended filtering function

pip install django-filter

The latest version django-filteris to keep django2.2above with, if not he will default djangoversion installed to the latest

We need to find themselves in return for their django-filterrelease

class BookView(GenericViewSet, ListModelMixin, CreateModelMixin):
    queryset = Book.objects
    serializer_class = BookSerializer
    filter_backends = [DjangoFilterBackend, ]
    filter_fields = ('name', 'id')  # 这里的字段不一样了 以前是search_fields
    
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

Search is also easy

127.0.0.1:8000/book/?name=雪山飞狐&id=3

image-20201111195007187

This oneNot fuzzy mode, The keyword cannot be found.

Six, sorting function

1. Configure in the view class

filter_backends =[OrderingFilter,]  # 可以混合使用
ordering_fields=['id','age']  # 先按照id 再按照年龄排序

Instructions

127.0.0.1:8000/book/?ordering=-id

image-20201111195714377

2. Sort after filtering

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter


class BookView(GenericViewSet, ListModelMixin, CreateModelMixin):
    queryset = Book.objects
    serializer_class = BookSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]  # 混合使用
    filter_fields = ('name', 'id')
    ordering_field = ('id', 'category')
    
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

use

127.0.0.1:8000/book/?name=雪山飞狐&ordering=-id

image-20201111200059773

Guess you like

Origin blog.csdn.net/A1L__/article/details/109630088