zoukankan      html  css  js  c++  java
  • ModelViewSet里的过滤、排序、分页、序列化设置

    先安装一下配置:

      安装DjangoRestFrameworkk
      pip install djangorestframeword==3.11.1(别的版本应该也可以,但是我目前不太清楚)
      pip install django_filter==2.3.0(同上)
      pip install markdown
    

    然后在settings里面配置添加:

      REST_FRAMEWORK = {
           'DEFAULT_THROTTLE_CLASSES': (
               'rest_framework.throttling.AnonRateThrottle',
               'rest_framework.throttling.UserRateThrottle',
           ),
           'DEFAULT_THROTTLE_RATES': {
               'anon': '100/day',
               'user': '1000/day'
           },
           'DEFAULT_FILTER_BACKENDS': ('django_filter.rest_framework.DjangoFilterBackend',)
      }
    

    跟路由还跟以前一样。
    子路由:

      from django.urls import path, include
      from apps.app01 import views
      from rest_framework.routers import DefaultRouter
    
      router = DefaultRouter()
      router.register("users", views.UserModelViewSet)(users是路径,UserModelViewSet是接口的名字)
    
      urlpatterns = [
            path('', include(router.urls)),
      ]
    

    views:

      from .models import *
      from .serializers import *
      from django_filters.rest_framework import DjangoFilterBackend
      from rest_framework.filters import OrderingFilter
      from rest_framework.pagination import PageNumberPagination
      from rest_framework.viewsets import ModelViewSet
    
      class UserModelViewSet(ModelViewSet):
          queryset = User.objects.all()
          serializer_class = UserSer
          pagination_class = StandardPageNumberPagination
          filter_backends = (OrderingFilter, DjangoFilterBackend)
          filter_filter = ['username', 'password']
          ordering_fields = ('password')
  • 相关阅读:
    正则表达式基础以及应用
    日常使用之css篇
    echarts的使用总结
    &#65279导致页面顶部空白一行
    vue.js单页面应用实例
    BFC的外边距折叠
    .net 跳出Frameset框架
    Cache缓存使用
    Kafka集群搭建及安全机制手册
    PHP学习笔记
  • 原文地址:https://www.cnblogs.com/kaka007/p/13893011.html
Copyright © 2011-2022 走看看