先安装一下配置:
安装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')