a. 自定义路由
from django.conf.urls import url, include
from web.views import s11_render
urlpatterns = [
url(r'^test/$', s11_render.TestView.as_view()),
url(r'^test\.(?P[a-z0-9]+)$', s11_render.TestView.as_view()),
url(r'^test/(?P[^/.]+)/$', s11_render.TestView.as_view()),
url(r'^test/(?P[^/.]+)\.(?P[a-z0-9]+)$', s11_render.TestView.as_view())
]
from rest_framework.views import APIView
from rest_framework.response import Response
from .. import models
class TestView(APIView):
def get(self, request, *args, **kwargs):
print(kwargs)
print(self.renderer_classes)
return Response('...')
b. 半自动路由
from django.conf.urls import url, include
from web.views import s10_generic
urlpatterns = [
url(r'^test/$', s10_generic.UserViewSet.as_view({'get': 'list', 'post': 'create'})),
url(r'^test/(?P\d+)/$', s10_generic.UserViewSet.as_view(
{'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from .. import models
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"
class UserViewSet(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
c. 全自动路由
from django.conf.urls import url, include
from rest_framework import routers
from web.views import s10_generic
router = routers.DefaultRouter()
router.register(r'users', s10_generic.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from .. import models
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"
class UserViewSet(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
全自动路由默认生成以下字段
from rest_framework.routers import DefaultRouter
route = DefaultRouter()
route.register('xxxxx',views.RouteView) # get:list, post: create
# url(r'^xxxxx/', views.RouteView.as_view({'get':'list','post':'create'})),
# url(r'^xxxxx\.(?P\w+)', views.RouteView.as_view({'get':'list','post':'create'})),
# url(r'^xxxxx/(?P\d+)', views.RouteView.as_view({'get':'retrieve','delete':'destroy','put':'update'})),
# url(r'^xxxxx/(?P\d+)\.(?P\w+)', views.RouteView.as_view({'get':'retrieve','delete':'destroy','put':'update'})),